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

320 views Asked by At

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.

2

There are 2 answers

0
kikito On BEST ANSWER

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)
0
Anon On

Not sure which Lua version does pico 8 use but for LuaJIT, you could try using loadstring and there is load for Lua5.2+ (I know, not the best solution):

for i = 1, 3 do
  local x
  loadstring("x = a_" .. tostring(i))()
  if x > 1 then 
    x = x - 1
    loadstring("a_" .. tostring(i) .. " = x")()
  end
end