Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - make bytecode

Tags:

lua

So, I've been asked to make a bytecode for the simpliest code:

print("Hello, world!")

But I have no idea how and I can't seem to find any information on how to make one... Can someone please help? I use Lua for Windows as a compiler. Thanks a lot

like image 876
Oti Na Nai Avatar asked Apr 04 '15 09:04

Oti Na Nai


People also ask

Does Lua compile to bytecode?

Pre-compiling does not imply faster execution because in Lua chunks are always compiled into bytecodes before being executed.

What is Lua bytecode?

Instruction Summary Lua bytecode instructions are 32-bits in size. All instructions have an opcode in the first 6 bits. Instructions can have the following fields: 'A' : 8 bits 'B' : 9 bits 'C' : 9 bits 'Ax' : 26 bits ('A', 'B', and 'C' together) 'Bx' : 18 bits ('B' and 'C' together) 'sBx' : signed Bx.


2 Answers

You can use the Lua compiler (see luac manual):

# 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!
like image 116
deltheil Avatar answered Oct 02 '22 19:10

deltheil


You can do it from Lua without luac using string.dump. Try for instance

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

If the code to be compiled is in a string, use load(s).

You can also save the file below as luac.luaand run it from the command line:

-- 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())
like image 30
lhf Avatar answered Oct 02 '22 18:10

lhf