我的添加命令不起作用

时间:2015-08-15 05:05:25

标签: lua

function read_file(file)
local data = io.open(file, "r")
for char in data:lines() do
    local num1 = 0
    local num2 = 0
    --Print statement
    if char:sub(1, 6) == "print>" then
        print(char:sub(7))
    end
    --Setting numbers command
    if char:sub(1, 5) == "num1>" then
        num1 = char:sub(6)
    end
    if char:sub(1, 5) == "num2>" then
        num2 = char:sub(6)
    end
    --The add command
    if char:sub(1, 5) == "add()" then
        print(num1 + num2)
    end
end
data:close()
end

function run()
while true do
    print("Open a file")
    file = io.read()
    print("")
    print("Opening file: "..file)
    print("")
    read_file(file)
    print("")
    print("Successfully compiled\n")
end
    end

run()

我的“设置数字命令”不起作用,变量num1和num2设置为0并且它们不会改变所以我被困了大约30分钟思考如何解决它而我无法想到如何修复它

1 个答案:

答案 0 :(得分:2)

  

变量num1和num2设置为0,它们不会改变

因为你在循环开始时将它们重置为0.

改变这个:

for char in data:lines() do
   local num1 = 0
   local num2 = 0
   ...

对此:

local num1 = 0
local num2 = 0
for char in data:lines() do
    ...

顺便说一下,你可以替换它:

local data = io.open(file, "r")
for char in data:lines() do
   ...
end
data:close()

有了这个,它做了同样的事情:

for lines in io.lines(file) do
   ...
end