2012-01-10 78 views
3

我一直在環顧四周,我一直無法找到任何對我有用的東西。我開始學習更多的Lua並開始製作一個簡單的計算器。我能夠將每個單獨的操作都放到單獨的程序中,但是當我嘗試將它們合併時,我無法使其運行。我的腳本,它現在是Lua - 如何使用另一個腳本中的函數?

require "io" 
require "operations.lua" 

do 
print ("Please enter the first number in your problem.") 
x = io.read() 
print ("Please enter the second number in your problem.") 
y = io.read() 
print ("Please choose the operation you wish to perform.") 
print ("Use 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division.") 
op = io.read() 
op = 1 then 
    function addition 
op = 2 then 
    function subtraction 
op = 3 then 
    function multiplication 
op = 4 then 
    function division 
print (answer) 
io.read() 
end 

和我operations.lua腳本

function addition 
    return answer = x+y 
end 

function subtraction 
    return answer = x-y 
end 

function multiplication 
    return answer = x*y 
end 

function division 
    return answer = x/y 
end 

我使用

if op = 1 then 
     answer = x+y 
     print(answer) 
if op = 2 then 
     answer = x-y 
     print(answer) 

嘗試和我這樣做,在完成各項操作。但它不起作用。我什至不能得到它返回的錯誤代碼,因爲它關閉得這麼快。我該怎麼辦?

回答

1

在您的示例中,進行以下更改:您require operations.lua沒有擴展名。在您的operations函數定義中包含參數。直接返回操作表達式而不返回像answer = x+y這樣的語句。

一起:

代碼operations.lua

function addition(x,y) 
    return x + y 
end 

--more functions go here... 

function division(x,y) 
    return x/y 
end 

代碼爲您的主機的Lua腳本:

require "operations" 

result = addition(5,7) 
print(result) 

result = division(9,3) 
print(result) 

一旦你得到的工作,嘗試重新加入io邏輯。

請記住,編碼後,您的功能將在全球定義。爲避免污染全局表,請考慮將operations.lua定義爲模塊。看看lua-users.org Modules Tutorial

+0

謝謝,當我回家時,我會盡力處理它。沒有SciTE的工作很難,因爲我無法找到解決它的錯誤。 – crazyman10123 2012-01-10 16:14:31

0

首先,學會使用命令行,以便您可以看到錯誤(在Windows上將是cmd.exe)。

二,將第二行更改爲require("operations")。您做這件事的方式是,翻譯人員期待一個目錄operations,其底層腳本lua.lua

+0

我會使用命令行,如果它沒有被阻止。現在我正在從我的學校電腦上工作,cmd.exe是一個被阻止的應用程序。我最初的要求是「操作」,但我將其更改爲operations.lua,因爲操作不起作用。我在我的家裏有SciTE,那是我昨天在處理腳本的主要部分時用來查看錯誤的。我會在家工作,看看我能否弄清楚。感謝您的幫助。 – crazyman10123 2012-01-10 15:23:59

1

if-then-else語法:

if op==1 then 
    answer = a+b 
elseif op==2 then 
    answer = a*b 
end 
print(answer) 

後:請檢查正確的函數聲明語法。

之後:return answer=x+y不正確。如果您想設置answer的值,請設置爲return。如果您想退還款項,請使用return x+y。我想你應該檢查Programming in Lua

+0

謝謝,我一直在if-then-else語法中遇到問題。我仍然是Lua的初學者,除了這個計算器之外,我只寫了兩個腳本。 – crazyman10123 2012-01-10 16:15:12

相關問題