Brain in a Bowl
Brain in a Bowl

Reputation: 13

Lua: set value on table name from variable

I'm quite new at Lua, but currently writing an inventory screen for a tic-80 project. I've been trying to create a function to draw buttons that change the value of a variable. A lot of googling and some experimentation led to this:

function drawButton(x,y,sprite,target,action). 
    [Drawing button stuff here]
    if md==true and mx<=x+12 and mx>=x and my<=y+12 and my>=y then
        _G[target]=action
    end
end

This works fine for a variable:

drawButton (12,12,0,"eqf",1)

But when I try to change the value in a table, it does nothing.

drawButton (12,12,0,"actors.player.eqf",1)

Is there a better approach that also supports tables? Thanks in advance!

Upvotes: 1

Views: 1059

Answers (1)

Vlad
Vlad

Reputation: 5847

"actors.player.eqf"

This does not address a field within nested tables.

If you want to alter a field in arbitrary table, you need to pass both - the table and required key to update. Something like this:

function drawButton(x,y,sprite,object,target,action)
    -- [Drawing button stuff here]
    if md==true and mx<=x+12 and mx>=x and my<=y+12 and my>=y then
        object[target]=action
    end
end

drawButton (12,12,0, _G, "eqf",1)
drawButton (12,12,0, actors.player, "eqf",1)

Upvotes: 1

Related Questions