0

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 Answers1

3

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.

DarkWiiPlayer
  • 6,871
  • 3
  • 23
  • 38
  • Thank you very much. I'm using flags because I'm coding in pico-8 and thats the built in system. For some reason, flag_obj[flag] still gives me a syntax error though, I'm going to assume it's something relating to pico – digital_drako May 07 '21 at 22:17