Lua - 生成字节码

因此,我被要求为最简单的代码创建字节码:

print("Hello, world!")

但我不知道如何做,并且似乎找不到任何有关如何创建字节码的信息...有人可以帮忙吗? 我在Windows上使用Lua作为编译器。非常感谢!

点赞
用户1688185
用户1688185

你可以使用 Lua compiler(见 luac 手册):

# 默认输出是 "luac.out"
echo 'print("Hello, world!")' | luac -

# 你可以使用 Lua 解释器执行这个字节码
lua luac.out
# -> Hello, world!
2015-04-04 09:49:09
用户107090
用户107090

你可以使用 string.dump 在 Lua 中不使用 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())
2015-04-04 11:13:39