Lua equivalent of dictionary.get() method?

1.6k views Asked by At

How do I access a dictionary using a parameter?

In python I can do dictionary.get(param) Is there an equivalent to this in lua?

I want to do something like this:

function make_object_from_flag(x, y, flag)
 local flag_obj = {
    [1] = make_impassable_object(x, y),
    [2] = make_coin(x,y),
    [4] = make_screen_transition_object(x, y),
 }


 flag_obj.get(flag)
end
1

There are 1 answers

1
DarkWiiPlayer On BEST ANSWER

Lua only has a single data structure, which is essentially a map (or dictionary) just called "table".

Table indexing in Lua usually works using brackets [], just like python does with arrays.

So basically, as Egor Skriptunoff pointed out in his comment, you want flag_obj[flag] to access the value associated with the key flag in the table flag_obj.

Note though that using bit flags as is done in C is very uncommon and not very performant in Lua, and shouldn't normally be done unless there's some good reason for it.