1

Sorry in advance if this is an incorrect question. I'm fairly new to Lua and I'm not sure how to go about this. I want to access a variable stored in a table from a function variable. As far as I know there is no self-referencing tables before constructed.

An example would be this:

local bigTable = {
    a = {
        foo = 0,
        bar = function(y)
        print(foo) --Incorrect
        end
    }
}

What would be the best approach for this situation?

1
  • 1
    Define function bigTable.a.bar(y) print(bigTable.a.foo) end in the next statement after the bigTable definition. Commented Nov 12, 2019 at 23:34

2 Answers 2

1

What you want to do is to create a table first, and append the keys to it:

local a = {}
a.foo = 0
a.bar = function()
    print(a.foo)
end
local bigTable = {
    a = a
}

bigTable.a.bar() -- prints 0
Sign up to request clarification or add additional context in comments.

Comments

0
local bigTable = {
   a = {
      foo = 0,
      bar = function(self, ...)
         print(self.foo)
      end,
   }
}

-- Somewhere else in the code...

bigTable.a.bar(bigTable.a) --> 0
-- or the shorter but (almost) equivalent form:
bigTable.a:bar() --> prints 0

I anticipate your next question will be "What does the : do?", and for that there's lots of answers on SO already :)


Note that there's potential for a performance improvement here: if the above code gets called a lot, the bar method will be created again and again, so it could make sense to cache it; but that's pointless unless the surrounding code is already fast enough that this one allocation would have a noticeable impact on its runtime.

4 Comments

The line bar = function bigTable.a:bar(...) raises syntax error
Ah, sorry, that's because I had originally written it differently and then moved stuff around without double checking. Fixing it now ;)
The new version with bar = bar(self, ...) also gives syntax error
Ah, yes, I'm just dumb. Now it works, thanks for pointing out :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.