Skip to content

Commit

Permalink
feat: global NIL
Browse files Browse the repository at this point in the history
  • Loading branch information
mdwagner committed Dec 28, 2023
1 parent 4f2db04 commit 315c8e1
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
34 changes: 34 additions & 0 deletions spec/luajit_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
require "./spec_helper"

describe Luajit do
describe "global nil" do
it ".setup_global_nil" do
Luajit.run do |state|
Luajit.setup_global_nil(state)

state.execute(<<-'LUA').ok?.should be_true
local x = NIL
assert(type(x) == 'userdata')
assert(x ~= nil)
assert(tostring(x) == 'NIL')
LUA
end
end

it ".is_global_nil?" do
Luajit.run do |state|
Luajit.setup_global_nil(state)

state.execute(<<-'LUA').ok?.should be_true
return NIL
LUA
Luajit.is_global_nil?(state, -1).should be_true

state.execute(<<-'LUA').ok?.should be_true
return nil
LUA
Luajit.is_global_nil?(state, -1).should be_false
end
end
end
end
27 changes: 27 additions & 0 deletions src/luajit.cr
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,31 @@ module Luajit
ud_ptr = state.get_userdata(index, type.metatable)
Box(T).unbox(ud_ptr)
end

# Sets `NIL` as a global value with metatable name *mt_name*
#
# See `.is_global_nil?`
def self.setup_global_nil(state : LuaState, mt_name = "luajit_cr::__NIL__") : Nil
state.new_userdata(0_u64)
state.push({
"__tostring" => Luajit::LuaState::Function.new { |__state|
__state.push("NIL")
1
}
})
state.push_value(-1)
state.set_registry(mt_name)
state.set_metatable(-2)
state.set_global("NIL")
end

# Checks if value at *index* is the global `NIL` value with metatable name *mt_name*
def self.is_global_nil?(state : LuaState, index : Int32, mt_name = "luajit_cr::__NIL__") : Bool
begin
state.check_userdata!(index, mt_name)
true
rescue LuaError
false
end
end
end

0 comments on commit 315c8e1

Please sign in to comment.