diff --git a/c/lua/_demo/extraspace/extraspace.go b/c/lua/_demo/extraspace/extraspace.go new file mode 100644 index 00000000..75089a0c --- /dev/null +++ b/c/lua/_demo/extraspace/extraspace.go @@ -0,0 +1,42 @@ +package main + +import ( + "unsafe" + _ "unsafe" + + "github.com/goplus/llgo/c" + "github.com/goplus/llgo/c/lua" +) + +func GetData(L *lua.State) c.Int { + extra := (*int)(L.Getextraspace()) + L.Pushfstring(c.Str("Stored integer is: %d"), *extra) + return 1 +} + +func main() { + L := lua.Newstate__1() + defer L.Close() + + L.Openlibs() + + extra := (*int)(L.Getextraspace()) + *extra = 42 + + difference := uintptr(unsafe.Pointer(L)) - uintptr(L.Getextraspace()) + if difference == unsafe.Sizeof(uintptr(0)) { + c.Printf(c.Str("Extra space is pointer size\n"), unsafe.Sizeof(uintptr(0))) + } + + L.Pushcfunction(GetData) + L.Setglobal(c.Str("GetData")) + + if L.Dostring(c.Str("print(GetData())")) != lua.OK { + c.Printf(c.Str("Error: %s\n"), L.Tostring(-1)) + } +} + +/* Expected output: +Extra space is pointer size +Stored integer is: 42 +*/ diff --git a/c/lua/lua.go b/c/lua/lua.go index acbf69d1..c5e35da5 100644 --- a/c/lua/lua.go +++ b/c/lua/lua.go @@ -460,7 +460,9 @@ func (L *State) Closeslot(idx c.Int) {} ** =============================================================== */ -// #define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE)) +func (L *State) Getextraspace() c.Pointer { + return c.Pointer(uintptr(c.Pointer(L)) - EXTRASPACE) +} func (L *State) Tonumber(idx c.Int) Number { return L.Tonumberx(idx, nil) } func (L *State) Tostring(idx c.Int) *c.Char { return L.Tolstring(idx, nil) } func (L *State) Tointeger(idx c.Int) Integer { return L.Tointegerx(idx, nil) } diff --git a/c/lua/luaconf.go b/c/lua/luaconf.go index 65b37f68..03bac83c 100644 --- a/c/lua/luaconf.go +++ b/c/lua/luaconf.go @@ -1,5 +1,7 @@ package lua +import "unsafe" + /* ** {================================================================== ** Macros that affect the API and must be stable (that is, must be the @@ -20,6 +22,15 @@ const ( MAXSTACK = 1000000 ) +/* +@@ LUA_EXTRASPACE defines the size of a raw memory area associated with +** a Lua state with very fast access. +** CHANGE it if you need a different size. +*/ +const ( + EXTRASPACE = unsafe.Sizeof(uintptr(0)) +) + /* @@ LUA_IDSIZE gives the maximum size for the description of the source ** of a function in debug information.