Skip to content

Commit

Permalink
feat: binary chunk support
Browse files Browse the repository at this point in the history
  • Loading branch information
mdwagner committed Feb 18, 2024
1 parent 038a291 commit 43338f9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
18 changes: 18 additions & 0 deletions spec/lua_state_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -244,4 +244,22 @@ describe Luajit::LuaState do
end
end
end

describe "#load_chunk" do
it "works" do
Luajit.run do |state|
state.execute! <<-'LUA'
return function()
return 500
end
LUA
SpecHelper.assert_stack_size!(state, 1)

io = state.dump_chunk
state.load_chunk(io, "").ok?.should be_true

SpecHelper.assert_stack_size!(state, 2)
end
end
end
end
32 changes: 32 additions & 0 deletions src/luajit/lua_state.cr
Original file line number Diff line number Diff line change
Expand Up @@ -742,6 +742,38 @@ module Luajit
raise LuaError.default_handler(self, status) unless status.ok?
end

# Dumps a Lua function as a binary chunk at *index*
#
# Raises `LuaError` if operation fails
def dump_chunk(index : Int32 = -1) : IO::Memory
io = IO::Memory.new
proc = LibLuaJIT::Writer.new do |_L, _p, _sz, _ud|
_io = Box(typeof(io)).unbox(_ud)
slice = _p.as(Pointer(UInt8)).to_slice(_sz)
_io.write(slice)
0
end

push_value(index)
status = LibLuaJIT.lua_dump(self, proc, Box(typeof(io)).box(io))
pop(1)

unless status == 0
raise LuaError.new("Failed to dump lua function")
end

io.rewind
end

# Loads *io* as a Lua chunk
#
# *name* is the chunk name, used for debug information and error messages.
#
# See `#dump_chunk`
def load_chunk(io : IO::Memory, name : String) : LuaStatus
LuaStatus.new(LibLuaJIT.luaL_loadbuffer(self, io.buffer, io.size, name))
end

# Pops a key from the stack, and pushes a key-value pair from the
# table at *index* (the "next" pair after the given key).
#
Expand Down

0 comments on commit 43338f9

Please sign in to comment.