Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: implicit table creation with string keys - why the extra brackets?

Tags:

lua

Say that you want to create a Lua table, and all its keys are valid lua identifiers. Then you can use the key=value syntax:

local niceTable = { I=1, like=1, this=1, syntax=1 }

If however your strings are not "identifiable", then you have to use the ['key']=value syntax:

local operators = { ['*']="Why", ['+']="the", ['/']="brackets", ['?']='?' }

I'm a bit baffled about this. What are those brackets doing there? What do they mean?

like image 479
kikito Avatar asked Dec 22 '10 23:12

kikito


People also ask

What do square brackets mean in Lua?

Brackets are used as a general form of key creation, they give you ability to put any hashable object as a key - not only strings.

How does Lua tables work?

Lua uses a constructor expression {} to create an empty table. It is to be known that there is no fixed relationship between a variable that holds reference of table and the table itself. When we have a table a with set of elements and if we assign it to b, both a and b refer to the same memory.

Is everything in Lua a table?

Tables are a versatile data structure that can be used as arrays, dictionaries, objects, etc. However, Lua provides many types besides tables: numbers, booleans, closures (functions), strings (which are interned), coroutines, and something called userdata (which are typically pointers to something implemented in C).


1 Answers

They identify the contained string as a key in the resulting table. The first form, you could consider as equal to

local niceTable = {}
niceTable.I = 1;
niceTable.like = 1;

The second form is equal to

local operators = {}
operators['*'] = "Why";
operators['+'] = "The";

The difference is purely syntactic sugar, except where the first one uses identifiers, so it has to follow the identifier rules, such as doesn't start with a number and interpret-time constant, and the second form uses any old string, so it can be determined at runtime, for example, and a string that's not a legal identifier. However, the result is fundamentally the same. The need for the brackets is easily explained.

local var = 5;
local table = {
    var = 5;
};
-- table.var = 5;

Here, var is the identifier, not the variable.

local table = {
    [var] = 5;
};
-- table[5] = 5;

Here, var is the variable, not the identifier.

like image 164
Puppy Avatar answered Sep 27 '22 18:09

Puppy