Dictionaries in LUA

In Python I can simply do:

N = {
"key1":<value1>,
"key2":<value2>,
"key3":<value3>, 
"key4":<value4>
}

What’s the equivalent of this in LUA?

2 Likes
N = {
    key = value, -- key interpreted as string
    [nonStringKey] = value
}
1 Like
local Vehicles = {
        [BikeSpeed] = 2.8, 
        [CarSpeed] = 3.5
}

is only valid if BikeSpeed and CarSpeed are variables with non-nil values, and it probably doesn’t do what you want. If you want a dictionary where you can access the values with e.g. local theBikeSpeed = Vehicles.BikeSpeed then you need to specify the table literal like so:

local Vehicles = {
        BikeSpeed = 2.8, 
        CarSpeed = 3.5
}

Leaving out the []s makes Lua interpret the keys (the parts before =) as strings. Using the []s makes Lua use the value of whatever expression is inside the []s as the key, be they strings or any other valid key type (i.e. anything but nil). Those expressions can evaluate to strings too, so t = {a = 1} is equivalent to t = {["a"] = 1}.

It’s the same story for indexing into tables. Using the . operator makes Lua interpret the key as a string, or you can use any expression as a key using []s. E.g. print(t.a) is equivalent to print(t["a"]).

I can recommend the Lua 5.1 manual, it covers all this and more

2 Likes