kite
kite

Reputation: 297

lua: piggybacking multiple variables across 1 if statement

I have around 7+ variables: a=1, b=10, c=12...etc
I need to write an if statement for each that does this:

if var>0 then var-=1 end

If I need each of the variables to record their values after each iteration, is there a way for me to avoid writing out one if statement per variable? I tried defining them all in a table like:

a=1;b=2;c=3

local t = {a,b,c}
for _,v in pairs(t) do
    if v>0 then v-=1 end
end
a,b,c=t[1],t[2],t[3]    

This code failed though, not sure why. Ultimately I'm looking for more efficient way than simply writing the ifs. You can define efficient in terms of cost or tokens or both. The values used would be random, no pattern. The variable names can potentially be changed, i.e. a_1,a_2, a_3, its not ideal though.

Upvotes: 0

Views: 307

Answers (2)

luther
luther

Reputation: 5544

There are a couple of solutions. To shorten your code, you could write a function that processes the value and run it on each variable:

local function toward0(var)
  if var > 0 then
    return var - 1
  end
  return var
end

a = toward0(a)
b = toward0(b)
c = toward0(c)

You could also store the data in a table instead of in variables. Then you can process them in a loop:

local valuesThatNeedToBeDecremented = {a = 1, b = 10, c = 12}

for k, v in pairs(valuesThatNeedToBeDecremented) do
  if v > 0 then
    valuesThatNeedToBeDecremented[k] = v - 1
  end
end

Upvotes: 1

mourad
mourad

Reputation: 677

You forgot to reasign the new values to the table!

local a, b, c = 1, 2, 3
local t = {a, b, c}
for k, v in ipairs(t) do
    if v > 0 then v -= 1 end
    t[k] = v
end
a, b, c = t[1], t[2], t[3]
print(a, b, c)

Upvotes: 1

Related Questions