0

So I'm trying something which i think should be very easy, but I just can't get it to work...

Basically what I'm trying to do is:

myTable = {
  a = 1,
  b = a + 1
}

This is not working, I get the error that "a" is nil. Reasonable. What i have already tried is

myTable = {
  a = 1,
  b = myTable.a + 1
}

and

myTable = {
  a = 1,
  b = self.a + 1
}

But it gives me the error me that "myTable"/"self" is nil.

I got the feeling that the solution is rather simple but i couldn't find it out by myself and google wasn't that helpful as well.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Noe2302
  • 7
  • 4
  • Note that for attempt#3, there is no context for `self` (requires a method definition) so it would reference the global `self` (which would likely be `nil`). – Tom Blodget Oct 13 '17 at 16:39

1 Answers1

4

There's no way of doing this in one statement (at least not without calling any functions or using metatables). That's because in a statement like foo = bar, the foo variable isn't assigned until the bar expression has been evaluated.

In your second example, the myTable variable isn't assigned until the closing curly brace, so the myTable in myTable.a + 1 is treated as an unnassigned global variable, and gets a value of nil. The self in your third example is the same, only you don't try to assign anything to it later. (In Lua, self is only special inside functions written with the colon syntax.)

To do what you want to do, you have to do something like this:

myTable = {
    a = 1
}
myTable.b = myTable.a + 1

Or this:

local a = 1
myTable = {
    a = a,
    b = a + 1
}
Jack Taylor
  • 5,588
  • 19
  • 35