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)

然后我按照每个操作完成了这项工作。但它没起作用。我甚至无法得到返回的错误代码,因为它关闭得太快了。我应该怎么办?

原文链接 https://stackoverflow.com/questions/8803862

点赞
stackoverflow用户542190
stackoverflow用户542190

首先,学习使用命令行,这样你就可以看到错误(在 Windows 上是 cmd.exe)。

第二,在第二行中将代码更改为 require("operations")。以你的方式进行,则解释器期望有一个名为 operations 的目录,该目录下具有一条基础脚本 lua.lua

2012-01-10 13:31:44
stackoverflow用户7625
stackoverflow用户7625

在您的示例中,进行以下更改:在不带扩展名的情况下要求 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 模块教程

2012-01-10 15:26:01
stackoverflow用户934599
stackoverflow用户934599

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

2012-01-10 15:28:24