初学Lua:如何在Mac OS上从终端调用函数?
我是 Lua 新手,正在学习一些教程,尝试一些基本的东西,例如编写常见算法等。
但是我在 mac os 机器上使用 lua 解释器时遇到了一些问题。
例如,假设我们有一个名为“sample.lua”的文件,其中包含代码行:
function fib(n) return n<2 and n or fib(n-1)+fib(n-2) end
如何从终端运行该函数? 如果我不使用任何函数,我只需使用“lua script.lua”调用脚本 - 有效!
下一个问题是关于非编译和编译lua源的使用的基本理解。为什么lua代码无需编译就可以运行,就像我之前提到的(lua script.lua)?或者这个语句会暂时编译代码然后运行?
预先感
谢克里斯
I'm new to Lua and work around with some tutorials, try some basic stuff like coding common algorithms etc.
But I have some trouble while using the lua interpreter on my mac os machine.
For example let's say we have a file called 'sample.lua', holds the code line:
function fib(n) return n<2 and n or fib(n-1)+fib(n-2) end
How do I run that function from terminal?
If I don't use any function, I just call the script with 'lua script.lua' - works!
Next question points on the basic understanding between the usage of non-compiled and compiled lua-source. Why is lua code run without compiling, like I mentioned before (lua script.lua)? Or will this statement compile the code temporarily and run afterwards?
Thanks in advance
chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 -i 标志从终端运行 lua:
这将执行脚本,然后将解释器置于交互模式。然后您可以直接从交互式提示中调用该函数:
You can run lua from the terminal with the -i flag:
This will execute the script and then put the interpreter into interactive mode. Then you could call the function right from the interactive prompt:
要从终端运行该函数,您必须执行以下操作:
-e 只是告诉它执行以下字符串,该字符串加载您的文件“sample.lua”,然后打印
fib(3 )
到标准输出。不过我不知道你的第二个问题的答案。
To run that function from the terminal, you would have to do something like:
The -e there just tells it to execute the following string, which loads your file 'sample.lua' and then prints the result of
fib(3)
to stdout.I don't know the answer to your second question though.
Lua脚本在运行之前总是被编译成Lua VM指令。预编译脚本只需跳过此步骤。
Lua scripts are always compiled into Lua VM instructions before running. Precompiled scripts just skip this step.