Erin Palmer
Erin Palmer

Reputation: 13

Python eval() in Lua

I have the following Lua code:

ow = { {move, 4, 5, Down}, { }, ...}

...

if ow[n][1] == "move" then
    joypad.set({ ow[n][4] = true })

This code returns an error. I want to have it work as if I typed:

joypad.set({ Down = true })

In python I would handle this situation like:

eval('joypad.set({ {0} = true })'.format(ow[n][4]))

Is there a similar or different way I can do this in Lua?

Upvotes: 1

Views: 1103

Answers (2)

greatwolf
greatwolf

Reputation: 20878

To answer your other question, yes Lua does have something like eval -- it's called loadstring:

local setjoy = ("joypad.set { %s = true }"):format(ow[n][4])
loadstring(setjoy)()

But as Niccolo's answer has shown, there's a much more straightforward approach for what you're after.

Upvotes: 1

Niccolo M.
Niccolo M.

Reputation: 3413

You need to write it thus:

joypad.set({ [ow[n][4]] = true })

Note the brackets around "ow[n][4]".

...and you may omit the parentheses:

joypad.set{ [ow[n][4]] = true }

The rule is this: if a table key isn't a lexical identifier or string, you need to put it inside brackets.

Upvotes: 1

Related Questions