2015-08-15 47 views
0
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分鐘思考如何修復它,我不能想到如何解決它。我的添加命令不起作用

回答

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 
+0

謝謝老兄,我覺得這樣做愚蠢xD –