Lua 添加脚本中的索引无法正常工作
Lua indexes in adding script doesn't work properly
我在 lua 中有此代码(如果不好,请见谅)。
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)
我知道它有点低效,但我只需要它现在可用。基本上,它应该做的只是加数字。例如,我输入 57 + 38
,它工作正常并给出正确的计算,但是一旦我输入 3 个数字(例如,57 + 38 + 40
),它就会崩溃并且不给出正确答案。
根据您的 Lua 版本,您可以使用 load
或 loadstring
来显着简化此操作。
local tocalc = "57 + 38 + 40"
print("Result: " .. load("return " .. tocalc)())
您的算法正在额外添加中间项。
if workwith[doing] == "+" then
did = did + workwith[doing - 1] + workwith[doing + 1]
end
这里第一个“+”是 did + 57 + 38
,did 是 95。下一个“+”是 did + 38 + 40
,所以要将 38 添加到最终值两次。要解决此问题,您只需查看数字并将它们单独相加,而不是成对相加。
repeat
if workwith[doing] ~= "+" then
did = did + workwith[doing]
end
doing = doing + 1
until doing > lenOfWorkwith
该算法还有其他问题,我强烈建议使用我上面描述的使用负载的解决方案。
我在 lua 中有此代码(如果不好,请见谅)。
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)
我知道它有点低效,但我只需要它现在可用。基本上,它应该做的只是加数字。例如,我输入 57 + 38
,它工作正常并给出正确的计算,但是一旦我输入 3 个数字(例如,57 + 38 + 40
),它就会崩溃并且不给出正确答案。
根据您的 Lua 版本,您可以使用 load
或 loadstring
来显着简化此操作。
local tocalc = "57 + 38 + 40"
print("Result: " .. load("return " .. tocalc)())
您的算法正在额外添加中间项。
if workwith[doing] == "+" then
did = did + workwith[doing - 1] + workwith[doing + 1]
end
这里第一个“+”是 did + 57 + 38
,did 是 95。下一个“+”是 did + 38 + 40
,所以要将 38 添加到最终值两次。要解决此问题,您只需查看数字并将它们单独相加,而不是成对相加。
repeat
if workwith[doing] ~= "+" then
did = did + workwith[doing]
end
doing = doing + 1
until doing > lenOfWorkwith
该算法还有其他问题,我强烈建议使用我上面描述的使用负载的解决方案。