Lua - 生成字节码

5

所以,我被要求为最简单的代码制作字节码:

print("Hello, world!")

但我不知道如何制作它,似乎也找不到任何关于如何制作它的信息...有人可以帮忙吗?我使用Lua for Windows作为编译器。非常感谢

2个回答

5

您可以使用Lua编译器(请参阅luac手册):

# the default output is "luac.out"
echo 'print("Hello, world!")' | luac -

# you can execute this bytecode with the Lua interpreter
lua luac.out
# -> Hello, world!

我在哪里可以下载luac? - Oti Na Nai
它正式提供了Lua源代码。另请参阅包含Windows说明(例如LuaDist)的安装部分 - deltheil

3

您可以使用 Lua 中的 string.dump 而不需要使用 luac 来完成。例如尝试以下代码:

f=assert(io.open("luac.out","wb"))
assert(f:write(string.dump(assert(loadfile("foo.lua")))))
assert(f:close())

如果要编译的代码在字符串中,使用load(s)。您还可以将以下文件保存为luac.lua并从命令行运行:
-- bare-bones luac in Lua
-- usage: lua luac.lua file.lua

assert(arg[1]~=nil and arg[2]==nil,"usage: lua luac.lua file.lua")
f=assert(io.open("luac.out","wb"))
assert(f:write(string.dump(assert(loadfile(arg[1])))))
assert(f:close())

是的,但你当然可以在脚本中更改名称。或者将其调整为接收输出文件名作为arg[2]。您将不得不更改第一个assert - lhf
谢谢,这对我帮助最大。那么,我只需要给他们 luac.out 文件吗? - Oti Na Nai
是的,但如果您愿意,可以将其命名为bar.lua,因为Lua会透明地加载预编译的字节码。 - lhf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接