Search code examples
luapico-8

Lua/pico8: Converting str to variable without access to _G table


I'm looking to iterate over some similarly named variables. a_1,a_2,a_3=1,2,3
So that instead of using:

if a_1>0 then a_1-=1 end
if a_2>0 then a_2-=1 end
if a_3>0 then a_3-=1 end

I can do something like:

for i=1,3 do
  if a_'i'>1 then a_'i'-=1 end --syntax is wrong here
end

Not sure how to go about doing this, as stated there is no access to _G library in pico8. var-=1 is just var=var-1. Given there are functions like tostr() and tonum() was wondering if there was a tovar() kind of trick to this. Basically need a way to convert the i value to a letter in my variable name and concat it to the variable name...in the conditional statement. Or some alternative method if there is one.


Solution

  • In Lua, when in doubt, use a table.

    In this case you could put the 3 variable on a table at the start, and unpack them at the end:

    local a={a_1,a_2,a_3}
    for i=1,3 do
     if(a[i]>1) a[i]-=1 
    end
    a_1,a_2,a_3=unpack(a)