Home > Back-end >  Lua indexes in adding script doesn't work properly
Lua indexes in adding script doesn't work properly

Time:03-15

I have this code in lua (sorry if its bad).

function splitIntoTable(inputstr,sep)
  local t = {}
  for str in string.gmatch(inputstr,"([^" .. sep .. "] )") do
    table.insert(t,str)
  end
  return t
end

function displayList(table)
  for k, v in ipairs(table) do
    print(table[k])
  end
end

local tocalc = "57   38"

print("Inputted: " .. tocalc)
tocalc = "0 " .. tocalc
local workwith = splitIntoTable(tocalc," ")
local did = 0
local doing = 1
local lenOfWorkwith = 0

for k in pairs(workwith) do
  lenOfWorkwith = lenOfWorkwith   1
end

repeat
  if workwith[doing] == " " then
    did = did   workwith[doing - 1]   workwith[doing   1]
  end
  doing = doing   1
until doing > lenOfWorkwith

did = math.floor(did   0.5)

print("Result: " .. did)

I know it's a bit inefficient, but I just need it usable right now. Basically, what its supposed to do is simply plus numbers. For example, I put in 57 38, it works fine and gives me the correct calculation, but as soon as I put in 3 numbers (for example, 57 38 40), it breaks down and doesn't give the correct answer.

CodePudding user response:

You can simplify this significantly by using load or loadstring depending on your Lua version.

local tocalc = "57   38   40"
print("Result: " .. load("return " .. tocalc)())

Your algorithm is adding the middle term an additional time.

  if workwith[doing] == " " then
    did = did   workwith[doing - 1]   workwith[doing   1]
  end

Here on the first " " you will be did 57 38, so did will be 95. on the next " " you will have get did 38 40, causing 38 to be added to the final value twice. To fix this you should simply look at the numbers and add them individually not in pairs.

repeat
  if workwith[doing] ~= " " then
    did = did   workwith[doing]
  end
  doing = doing   1
until doing > lenOfWorkwith

The algorithm still has other issues, I strongly suggest using solution using load I described above.

  • Related