What is the meaning of 'attempt to index upvalue'

34.1k Views Asked by At

I am taking my first steps programming in Lua and get this error when I run my script:

attempt to index upvalue 'base' (a function value)

It's probably due to something very basic that I haven't grasped yet, but I can't find any good information about it when googling. Could someone explain to me what it means?

2

There are 2 best solutions below

1
AudioBubble On BEST ANSWER

In this case it looks base is a function, but you're trying to index it like a table (eg. base[5] or base.somefield).

The 'upvalue' part is just telling you what kind of variable base is, in this case an upvalue (aka external local variable).

0
GoojajiGreg On

One "local" too many?

As Mike F explained, an "upvalue" is an external local variable. This error often occurs when a variable has been declared local in a forward declaration and then declared local again when it is initialized. This leaves the forward declared variable with a value of nil. This code snippet demonstrates what not to do:

 local foo -- a forward declaration 

 local function useFoo()
      print( foo.bar )  -- foo is an upvalue and this will produce the error in question
                        -- not only is foo.bar == nil at this point, but so is foo
 end

 local function f()

     -- one LOCAL too many coming up...

     local foo = {}   -- this is a **new** foo with function scope

     foo.bar = "Hi!"

     -- the local foo has been initialized to a table
     -- the upvalue (external local variable) foo declared above is not
     -- initialized

     useFoo()
 end 

 f()

In this case, removing the local in front of foo when it is initialized in f() fixes the example, i.e.

foo = {}
foo.bar = "Hi!"

Now the call to useFoo() will produce the desired output

Hi!