【问题标题】:Lua - How do I use a function from another script?Lua - 如何使用另一个脚本中的函数?
【发布时间】:2012-02-06 21:35:04
【问题描述】:

我一直在四处寻找,但找不到任何对我有用的东西。我开始学习更多 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)

我完成了每个操作。但它不起作用。我什至无法得到它返回的错误代码,因为它关闭得太快了。我该怎么办?

【问题讨论】:

    标签: function lua calculator


    【解决方案1】:

    在您的示例中,进行以下更改:您 require operations.lua 没有扩展名。在operations 函数定义中包含参数。直接返回操作表达式,而不是返回像answer = x+y 这样的语句。

    大家一起:

    操作代码.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

    【讨论】:

    • 谢谢,我回家后会努力解决的。没有访问 SciTE 就很难工作,因为我无法显示错误以供我解决。
    【解决方案2】:

    正确的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

    【讨论】:

    • 谢谢,我在使用 if-then-else 语法时遇到了问题。我还是个 Lua 初学者,除了这个计算器,我只写过两个脚本。
    【解决方案3】:

    首先,学习使用命令行,以便查看错误(在 Windows 上为 cmd.exe)。

    其次,将第二行改为require("operations")。按照你的做法,解释器需要一个目录 operations 和一个底层脚本 lua.lua

    【讨论】:

    • 如果没有被阻止,我会使用命令行。现在我在我的学校电脑上工作,而 cmd.exe 是一个被阻止的应用程序。我最初将它作为需要“操作”,但我将其更改为操作.lua,因为操作不起作用。我家有 SciTE,这就是我昨天在编写脚本的主要部分时用来查看错误的工具。我会在家里研究它,看看我是否能解决这个问题。感谢您的帮助。
    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 2019-01-31
    • 2017-01-20
    • 2017-07-30
    • 1970-01-01
    • 2015-07-14
    • 2019-10-15
    • 1970-01-01
    相关资源
    最近更新 更多