Skip to content

Commit 43338f9

Browse files
committed
feat: binary chunk support
1 parent 038a291 commit 43338f9

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

spec/lua_state_spec.cr

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,4 +244,22 @@ describe Luajit::LuaState do
244244
end
245245
end
246246
end
247+
248+
describe "#load_chunk" do
249+
it "works" do
250+
Luajit.run do |state|
251+
state.execute! <<-'LUA'
252+
return function()
253+
return 500
254+
end
255+
LUA
256+
SpecHelper.assert_stack_size!(state, 1)
257+
258+
io = state.dump_chunk
259+
state.load_chunk(io, "").ok?.should be_true
260+
261+
SpecHelper.assert_stack_size!(state, 2)
262+
end
263+
end
264+
end
247265
end

src/luajit/lua_state.cr

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,38 @@ module Luajit
742742
raise LuaError.default_handler(self, status) unless status.ok?
743743
end
744744

745+
# Dumps a Lua function as a binary chunk at *index*
746+
#
747+
# Raises `LuaError` if operation fails
748+
def dump_chunk(index : Int32 = -1) : IO::Memory
749+
io = IO::Memory.new
750+
proc = LibLuaJIT::Writer.new do |_L, _p, _sz, _ud|
751+
_io = Box(typeof(io)).unbox(_ud)
752+
slice = _p.as(Pointer(UInt8)).to_slice(_sz)
753+
_io.write(slice)
754+
0
755+
end
756+
757+
push_value(index)
758+
status = LibLuaJIT.lua_dump(self, proc, Box(typeof(io)).box(io))
759+
pop(1)
760+
761+
unless status == 0
762+
raise LuaError.new("Failed to dump lua function")
763+
end
764+
765+
io.rewind
766+
end
767+
768+
# Loads *io* as a Lua chunk
769+
#
770+
# *name* is the chunk name, used for debug information and error messages.
771+
#
772+
# See `#dump_chunk`
773+
def load_chunk(io : IO::Memory, name : String) : LuaStatus
774+
LuaStatus.new(LibLuaJIT.luaL_loadbuffer(self, io.buffer, io.size, name))
775+
end
776+
745777
# Pops a key from the stack, and pushes a key-value pair from the
746778
# table at *index* (the "next" pair after the given key).
747779
#

0 commit comments

Comments
 (0)