diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6fa8730 --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +vendor/ + +# Visual Studio Code directory +.vscode/ + diff --git a/.travis.yml b/.travis.yml index a80e062..9e0858c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,14 +1,5 @@ language: go dist: xenial -before_install: - - sudo add-apt-repository ppa:vbernat/haproxy-1.6 -y - - sudo apt-get -qq update - - sudo apt-get install -y liblua5.1-dev - - sudo apt-get install -y liblua5.2-dev - - sudo apt-get install -y liblua5.3-dev install: true script: - - go test -v github.com/aarzilli/golua/lua - - go test -v -tags lua52 github.com/aarzilli/golua/lua - - go test -v -tags lua53 github.com/aarzilli/golua/lua - + - go test -v github.com/vxcontrol/golua/lua diff --git a/README.md b/README.md index f948f43..50e7c67 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,17 @@ Go Bindings for the lua C API ========================= -[![Build Status](https://travis-ci.org/aarzilli/golua.svg?branch=master)](https://travis-ci.org/aarzilli/golua) +[![Build Status](https://travis-ci.org/vxcontrol/golua.svg?branch=master)](https://travis-ci.org/vxcontrol/golua) Simplest way to install: - # go get github.com/aarzilli/golua/lua + # go get -u github.com/vxcontrol/golua/lua + +Will work as long as your compiler can find a shared object called lua5.1 on linux, or lua anywhere else. +If your linux system uses "lua" as the shared object name for lua (for example, Fedora Core does this) you can install using: + + # go get -u github.com/vxcontrol/golua/lua + You can then try to run the examples: @@ -15,19 +21,6 @@ You can then try to run the examples: $ go run panic.go $ go run userdata.go -This library is configured using build tags. By default it will look for a library (or "shared object") called: - -* lua5.1 on Linux and macOS -* lua on Windows -* lua-5.1 on FreeBSD - -If this doesn't work `-tags luadash5.1` can be used to force `lua-5.1`, and `-tags llua` can be used to force `lua`. - -If you want to statically link to liblua.a you can do that with `-tags luaa`. Luajit can also be used by -specifying `-tags luajit`. - -The library uses lua5.1 by default but also supports lua5.2 by specifying `-tags lua52`, lua5.3 by -specifying `-tags lua53`, and lua5.4 by specifying `-tags lua54`. QUICK START --------------------- @@ -110,21 +103,13 @@ ON THREADS AND COROUTINES 'lua.State' is not thread safe, but the library itself is. Lua's coroutines exist but (to my knowledge) have never been tested and are likely to encounter the same problems that errors have, use at your own peril. -ODDS AND ENDS ---------------------- - -* If you want to build against lua5.2, lua5.3, or lua5.4 use the build tags lua52, lua53, or lua54 respectively. -* Compiling from source yields only a static link library (liblua.a), you can either produce the dynamic link library on your own or use the `luaa` build tag. - LUAJIT --------------------- -To link with [luajit-2.0.x](http://luajit.org/luajit.html), you can use CGO_CFLAGS and CGO_LDFLAGS environment variables +To link with [luajit-2.1.x](http://luajit.org/luajit.html), you can use CGO_CFLAGS and CGO_LDFLAGS environment variables ``` -$ CGO_CFLAGS=`pkg-config luajit --cflags` -$ CGO_LDFLAGS=`pkg-config luajit --libs-only-L` -$ go get -f -u -tags luajit github.com/aarzilli/golua/lua +$ go get -f -u github.com/vxcontrol/golua/lua ``` CONTRIBUTORS diff --git a/_example/alloc.go b/_example/alloc.go index cd3b437..aa075d4 100644 --- a/_example/alloc.go +++ b/_example/alloc.go @@ -1,12 +1,15 @@ package main -import "github.com/aarzilli/golua/lua" -import "unsafe" -import "fmt" +import ( + "fmt" + "unsafe" + + "github.com/vxcontrol/golua/lua" +) var refHolder = map[unsafe.Pointer][]byte{} -//a terrible allocator! +// AllocatorF a terrible allocator! //meant to be illustrative of the mechanics, //not usable as an actual implementation func AllocatorF(ptr unsafe.Pointer, osize uint, nsize uint) unsafe.Pointer { @@ -31,6 +34,7 @@ func AllocatorF(ptr unsafe.Pointer, osize uint, nsize uint) unsafe.Pointer { return ptr } +// A2 a wrapper to allocator func A2(ptr unsafe.Pointer, osize uint, nsize uint) unsafe.Pointer { return AllocatorF(ptr, osize, nsize) } diff --git a/_example/basic.go b/_example/basic.go index 28f766d..2e999ac 100644 --- a/_example/basic.go +++ b/_example/basic.go @@ -1,7 +1,10 @@ package main -import "github.com/aarzilli/golua/lua" -import "fmt" +import ( + "fmt" + + "github.com/vxcontrol/golua/lua" +) func test(L *lua.State) int { fmt.Println("hello world! from go!") diff --git a/_example/dump_load.go b/_example/dump_load.go index 9d8c95b..4fef232 100644 --- a/_example/dump_load.go +++ b/_example/dump_load.go @@ -3,7 +3,7 @@ package main import ( "fmt" - "github.com/aarzilli/golua/lua" + "github.com/vxcontrol/golua/lua" ) // dumpAndLoadTest: dump a function chunk to bytecodes, then load bytecodes and call function diff --git a/_example/error.go b/_example/error.go index 5ae65d9..9779b40 100644 --- a/_example/error.go +++ b/_example/error.go @@ -1,9 +1,12 @@ package main -import "github.com/aarzilli/golua/lua" -import "fmt" -import "errors" -import "os" +import ( + "errors" + "fmt" + "os" + + "github.com/vxcontrol/golua/lua" +) func testDefault(L *lua.State) { err := L.DoString("print(\"Unknown variable\" .. x)") diff --git a/_example/panic.go b/_example/panic.go index ef8b9d7..b468432 100644 --- a/_example/panic.go +++ b/_example/panic.go @@ -1,36 +1,38 @@ package main -import "github.com/aarzilli/golua/lua" -import "fmt" +import ( + "fmt" -func test(L *lua.State) int { - fmt.Println("hello world! from go!") - return 0 -} + "github.com/vxcontrol/golua/lua" +) func main() { - - var L *lua.State + var ( + currentPanicf lua.LuaGoFunction + L *lua.State + ) L = lua.NewState() defer L.Close() L.OpenLibs() - currentPanicf := L.AtPanic(nil) - currentPanicf = L.AtPanic(currentPanicf) - newPanic := func(L1 *lua.State) int { - fmt.Println("I AM PANICKING!!!", currentPanicf) + newPanicf := func(L1 *lua.State) int { + le := (&lua.LuaError{}).New(L1, 0, L1.ToString(-1)) + fmt.Println("I AM PANICKING!!!", currentPanicf, le.Msg) if currentPanicf != nil { return currentPanicf(L1) } return 1 } - - L.AtPanic(newPanic) + currentPanicf = L.AtPanic(newPanicf) //force a panic - L.PushNil() + test := func(L1 *lua.State) int { + L1.RaiseError("panic check") + return 0 + } + L.PushGoFunction(test) L.Call(0, 0) fmt.Println("End") diff --git a/_example/quickstart.go b/_example/quickstart.go index bffca02..817c966 100644 --- a/_example/quickstart.go +++ b/_example/quickstart.go @@ -1,6 +1,6 @@ package main -import "github.com/aarzilli/golua/lua" +import "github.com/vxcontrol/golua/lua" func adder(L *lua.State) int { a := L.ToInteger(1) diff --git a/_example/userdata.go b/_example/userdata.go index 5cd56b3..34fbfa8 100644 --- a/_example/userdata.go +++ b/_example/userdata.go @@ -1,8 +1,11 @@ package main -import "github.com/aarzilli/golua/lua" -import "unsafe" -import "fmt" +import ( + "fmt" + "unsafe" + + "github.com/vxcontrol/golua/lua" +) type Userdata struct { a, b int diff --git a/go.mod b/go.mod index 9a21e99..0973ced 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ -module github.com/aarzilli/golua +module github.com/vxcontrol/golua -go 1.15 +go 1.13 + +require github.com/vxcontrol/rmx v0.0.0-20210315190445-0c5e1f972da6 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..2b0fd5f --- /dev/null +++ b/go.sum @@ -0,0 +1,8 @@ +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/gls v0.0.0-20190610040709-84558782a674 h1:1n+vuTzNkmbDn73+cV6Hz25pkC7qX9u2QHaz/jA4x2g= +github.com/modern-go/gls v0.0.0-20190610040709-84558782a674/go.mod h1:I8AX+yW//L8Hshx6+a1m3bYkwXkpsVjA2795vP4f4oQ= +github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/vxcontrol/rmx v0.0.0-20210315190445-0c5e1f972da6 h1:a4ML+o1WlNw8gOGautso1TTfETirOsUNC0Xpr+yWQLo= +github.com/vxcontrol/rmx v0.0.0-20210315190445-0c5e1f972da6/go.mod h1:tWgKOCwhzgp7K6XMYelYlTqB/v4/VubHgr2WOmd3XFI= diff --git a/lua/c-golua.c b/lua/c-golua.c index 79342af..9649239 100644 --- a/lua/c-golua.c +++ b/lua/c-golua.c @@ -1,8 +1,9 @@ -#include -#include -#include +#include "golua.h" + #include #include + +//lint:ignore C/C++(1696) #include "_cgo_export.h" #define MT_GOFUNCTION "GoLua.GoFunction" @@ -10,9 +11,36 @@ #define GOLUA_DEFAULT_MSGHANDLER "golua_default_msghandler" -static const char GoStateRegistryKey = 'k'; //golua registry key +// golua registry key, main states only, non non-main coroutines. +// The address of this constant is used as a unique +// lightuserdata key. +static const char GoMainStatesKey = 'k'; + +// Within one main state, store the main state (at 1), +// plus all other coroutines at uniqArray[pos > 1]. +// Stored in the per state Lua registry. +// The address of this constant is used as a unique +// lightuserdata key. +static const char GoWithinStateUniqArrayKey = 'u'; //golua registry key, uniq array. + +// Within one main state's +// the reverseUniqMap maps *lua_State -> uPos +// Stored in the per state Lua registry. +// The address of this constant is used as a unique +// lightuserdata key. +static const char GoWithinStateRevUniqMap = 'r'; //in golua registry, reverse uniq map + static const char PanicFIDRegistryKey = 'k'; +/* makes sure we compile in atoll/_atoi64 if available.*/ +long long int wrapAtoll(const char *nptr) +{ +#if _WIN32 || _WIN64 + return _atoi64(nptr); +#else + return atoll(nptr); +#endif +} /* taken from lua5.2 source */ void *testudata(lua_State *L, int ud, const char *tname) @@ -56,47 +84,96 @@ unsigned int* clua_checkgosomething(lua_State* L, int index, const char *desired } } +static lua_State* clua_get_main_thread(lua_State* L) { + // experiment: can we get main from uniqArray[1]; it should be there. + int top = lua_gettop(L); + lua_pushlightuserdata(L, (void*)&GoWithinStateUniqArrayKey); + lua_gettable(L, LUA_REGISTRYINDEX); // pushes value onto top of stack + // stack: uniqArray + + if (lua_isnil(L,-1)) { + printf("\n debug: arg. nil back for UniqKey lookup.\n"); + exit(-1); + } + + lua_pushnumber(L, 1); + // stack: 1, uniqArray + lua_gettable(L, -2); + // stack: main *lua_State, uniqArray + + int ty = lua_type(L, -1); + + lua_State* mainThread = lua_tothread(L, -1); + + lua_settop(L, top); + + return mainThread; +} + size_t clua_getgostate(lua_State* L) { size_t gostateindex; + //get gostate from registry entry - lua_pushlightuserdata(L,(void*)&GoStateRegistryKey); - lua_gettable(L, LUA_REGISTRYINDEX); - gostateindex = (size_t)lua_touserdata(L,-1); - lua_pop(L,1); + lua_pushlightuserdata(L,(void*)&GoMainStatesKey); + lua_gettable(L, LUA_REGISTRYINDEX); // pushes value onto top of stack + + // 'k' is now a map from lua_State* to index + // push key + lua_pushthread(L); + // stack is now: + // key + // map + lua_gettable(L, -2); + // stack is now + // index value + // map + + // if nil, enter it, so it is recorded. + if (lua_isnil(L, -1)) { + gostateindex = (size_t)(0); + } else { + gostateindex = (size_t)lua_tonumber(L, -1); + } + lua_pop(L, 2); return gostateindex; } - //wrapper for callgofunction -int callback_function(lua_State* L) +int callback_function(lua_State* coro) { int r; - unsigned int *fid = clua_checkgosomething(L, 1, MT_GOFUNCTION); - size_t gostateindex = clua_getgostate(L); - //remove the go function from the stack (to present same behavior as lua_CFunctions) - lua_remove(L,1); - return golua_callgofunction(gostateindex, fid!=NULL ? *fid : -1); + unsigned int *fid = clua_checkgosomething(coro, 1, MT_GOFUNCTION); + size_t coro_index = clua_getgostate(coro); + lua_State* mainThread = clua_get_main_thread(coro); + size_t mainIndex = clua_getgostate(mainThread); + + // jea: the metatable is on the stack. + //remove the userdata metatable (go function??) from the stack (to present same behavior as lua_CFunctions) + lua_remove(coro, 1); + + return golua_callgofunction(coro, coro_index, mainIndex, mainThread, fid!=NULL ? *fid : -1); } //wrapper for gchook int gchook_wrapper(lua_State* L) { - //printf("Garbage collection wrapper\n"); unsigned int* fid = clua_checkgosomething(L, -1, NULL); - size_t gostateindex = clua_getgostate(L); - if (fid != NULL) - return golua_gchook(gostateindex,*fid); + if (fid != NULL) { + lua_State* mainThread = clua_get_main_thread(L); + size_t main_index = clua_getgostate(mainThread); + return golua_gchook(main_index, *fid); + } return 0; } -unsigned int clua_togofunction(lua_State* L, int index) +int clua_togofunction(lua_State* L, int index) { unsigned int *r = clua_checkgosomething(L, index, MT_GOFUNCTION); return (r != NULL) ? *r : -1; } -unsigned int clua_togostruct(lua_State *L, int index) +int clua_togostruct(lua_State *L, int index) { unsigned int *r = clua_checkgosomething(L, index, MT_GOINTERFACE); return (r != NULL) ? *r : -1; @@ -110,11 +187,14 @@ void clua_pushgofunction(lua_State* L, unsigned int fid) lua_setmetatable(L, -2); } -static int callback_c (lua_State* L) +static int callback_c(lua_State* coro) { - int fid = clua_togofunction(L,lua_upvalueindex(1)); - size_t gostateindex = clua_getgostate(L); - return golua_callgofunction(gostateindex,fid); + int fid = clua_togofunction(coro, lua_upvalueindex(1)); + size_t coro_index = clua_getgostate(coro); + lua_State* mainThread = clua_get_main_thread(coro); + size_t main_index = clua_getgostate(mainThread); + + return golua_callgofunction(coro, coro_index, main_index, mainThread, fid); } void clua_pushcallback(lua_State* L) @@ -132,18 +212,285 @@ void clua_pushgostruct(lua_State* L, unsigned int iid) int default_panicf(lua_State *L) { - const char *s = lua_tostring(L, -1); + char *s = (char *)lua_tostring(L, -1); + lua_State* mainThread = clua_get_main_thread(L); + size_t main_index = clua_getgostate(mainThread); + + go_default_panic_msghandler(L, main_index, s); + printf("Lua unprotected panic: %s\n", s); abort(); + return 0; } -void clua_setgostate(lua_State* L, size_t gostateindex) +int panic_msghandler(lua_State *L) { - lua_atpanic(L, default_panicf); - lua_pushlightuserdata(L,(void*)&GoStateRegistryKey); - lua_pushlightuserdata(L, (void*)gostateindex); - //set into registry table + char *s = (char *)lua_tolstring(L, -1, NULL); + lua_State* mainThread = clua_get_main_thread(L); + size_t main_index = clua_getgostate(mainThread); + + go_panic_msghandler(L, main_index, s); + return 1; +} + +void create_uniqArray(lua_State* L) { + // stack: ... + + lua_newtable(L); + // stack: newtable, ... + + lua_pushlightuserdata(L,(void*)&GoWithinStateUniqArrayKey); + // stack: ukey, newtable, ... + + lua_insert(L, -2); + // stack: newtable, ukey, ... + lua_settable(L, LUA_REGISTRYINDEX); + // stack: ... + + // and create the reverse uniq map: *lua_State -> uPos + lua_newtable(L); + // stack: newtable, ... + + lua_pushlightuserdata(L,(void*)&GoWithinStateRevUniqMap); + // stack: urevkey, newtable, ... + + lua_insert(L, -2); + // stack: newtable, urevkey, ... + + lua_settable(L, LUA_REGISTRYINDEX); + // stack: ... +} + +// return 1 if created, 0 if already existed. +int clua_create_uniq_array_if_not_exists(lua_State* L) { + // stack: ... + + lua_pushlightuserdata(L,(void*)&GoWithinStateUniqArrayKey); + // stack: ukey, ... + lua_gettable(L, LUA_REGISTRYINDEX); + // stack: (uniqArray or nil), ... + + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + // stack: ... + create_uniqArray(L); + // stack: ... + return 1; + } + lua_pop(L, 1); + // stack: ... + return 0; +} + +int clua_add_thread_to_uniq_array_and_rev_uniq(lua_State* L); + +// clua_known_coro returns the index +// of L in uniqArray, adding L to +// uniqArray and revUniqMap if it +// is not already present in revUniqMap. +// +// POST INVAR: +// On return of value uPos, uniqArray[uPos] == L +// and revUniqMap[L] == uPos. +// +// The returned value will be >= 1. +// +int clua_dedup_coro(lua_State* L) +{ + if (1 == clua_create_uniq_array_if_not_exists(L)) { + return clua_add_thread_to_uniq_array_and_rev_uniq(L); + } + + int top = lua_gettop(L); + + // use revUniqMap, for O(1) lookup. + + // store pos into revUniqMap too, for O(1) coroutine lookup. + lua_pushlightuserdata(L, (void*)&GoWithinStateRevUniqMap); + // stack: revkey + + lua_gettable(L, LUA_REGISTRYINDEX); + // stack: revUniqMap + + int isMain = lua_pushthread(L); + // stack: thread, revUniqMap + + lua_gettable(L, -2); + // stack: (pos or nil), revUniqMap + + if (lua_isnil(L, -1)) { + // stack: nil, revUniqMap + + // not previously known + lua_settop(L, top); + // stack clean + + // add it + return clua_add_thread_to_uniq_array_and_rev_uniq(L); + } + + // stack: pos, revUniqMap + int res = (int)lua_tonumber(L, -1); + + lua_settop(L, top); + // stack clean + return res; +} + +int clua_add_thread_to_uniq_array_and_rev_uniq(lua_State* L) { + // + // Do the equivalent of: table.insert(uniqueArray, L) + // and then revUniq[L] = #uniqArray (==uPos) + + // stack: ... + int top = lua_gettop(L); + + lua_pushlightuserdata(L,(void*)&GoWithinStateUniqArrayKey); + // stack: ukey, ... + + lua_gettable(L, LUA_REGISTRYINDEX); + // stack: uniqArray, ... + + // jea: now store the actual thread in uniqArray + // + lua_pushthread(L); + // stack: thread, uniqArray, ... + + // append to array at -2 + int pos = lua_objlen(L, -2) + 1; /* first empty element */ + + lua_rawseti(L, -2, pos); /* t[pos] = v; and pops v from the top of the stack*/ + // stack: uniqArray, ... + + lua_pop(L, 1); + // stack: ... + + // Phase 2: + // + // store pos into revUniqMap too, for O(1) coroutine lookup. + lua_pushlightuserdata(L, (void*)&GoWithinStateRevUniqMap); + // stack: revkey, ... + + lua_gettable(L, LUA_REGISTRYINDEX); + // stack: revUniqMap, ... + + lua_pushthread(L); + // stack: thread, revUniqMap, ... + + lua_pushnumber(L, (double)pos); + // stack: pos, thread, revUniqMap, ... + + lua_settable(L, -3); + // stack: revUniqMap, ... + + lua_settop(L, top); + // stack clean + + return pos; +} + +int clua_setgostate(lua_State* L, size_t gostateindex) +{ + int ret = 0; + int top = lua_gettop(L); + + lua_atpanic(L, default_panicf); + lua_pushlightuserdata(L,(void*)&GoMainStatesKey); + + // + // store L into a table that maps lua_State* -> gostateindex. + // Call the table the Lmap. It maps L to an index. + // + lua_gettable(L, LUA_REGISTRYINDEX); // pops the key + // does it already exist, or did we get nil back? + if (lua_isnil(L, -1)) { + // doesn't exist yet, need to create it the first time. + lua_pop(L, 1); // get rid of the nil + lua_newtable(L); + + // save Lmap into lua registry under GoMainStatesKey. + + // stack: + // Lmap + lua_pushvalue(L, -1); + // stack: + // Lmap + // Lmap + + // get the key + lua_pushlightuserdata(L,(void*)&GoMainStatesKey); + // stack is now: + // key + // Lmap + // Lmap + + lua_insert(L, -2); + // stack should now be ready for lua_settable: + // Lmap + // key + // Lmap + + //set into registry table + lua_settable(L, LUA_REGISTRYINDEX); + // stack: + // Lmap + + // and create the uniq array too, at the same time. + clua_create_uniq_array_if_not_exists(L); + + // stack: Lmap + } + // INVAR: our Lmap is at top of stack, -1 position. + // stack: Lmap + + // does our key already exist in the Lmap? + // If not, then append to the uniqArray. + // key + lua_pushthread(L); + // stack: key, Lmap + + lua_gettable(L, -2); + // stack: nil, Lmap OR priorValue, Lmap + + if (!lua_isnil(L, -1)) { + // stack: priorValue, Lmap + // no duplicate insert into Lmap needed + lua_settop(L, top); + // stack clean. + + // should be returning 1 always, indicating + // a main coroutine. + return clua_dedup_coro(L); + } + + // stack: thread, Lmap + lua_pop(L, 1); + // stack: Lmap + + // This thread, L, is not known to Lmap. + ret = clua_add_thread_to_uniq_array_and_rev_uniq(L); + + // stack: Lmap + + // Finally, populate the Lmap + + // key + lua_pushthread(L); + // stack: key, Lmap + + // value + lua_pushnumber(L, gostateindex); + // stack: value, key, Lmap + + // store key:value in map + lua_settable(L, -3); + // stack: Lmap + + // cleanup stack, remove Lmap + lua_settop(L, top); + + return ret; } /* called when lua code attempts to access a field of a published go object */ @@ -163,9 +510,10 @@ int interface_index_callback(lua_State *L) return 1; } - size_t gostateindex = clua_getgostate(L); + lua_State* mainThread = clua_get_main_thread(L); + size_t main_index = clua_getgostate(mainThread); - int r = golua_interface_index_callback(gostateindex, *iid, field_name); + int r = golua_interface_index_callback(L, main_index, *iid, field_name); if (r < 0) { @@ -195,9 +543,10 @@ int interface_newindex_callback(lua_State *L) return 1; } - size_t gostateindex = clua_getgostate(L); + lua_State* mainThread = clua_get_main_thread(L); + size_t main_index = clua_getgostate(mainThread); - int r = golua_interface_newindex_callback(gostateindex, *iid, field_name); + int r = golua_interface_newindex_callback(L, main_index, *iid, field_name); if (r < 0) { @@ -210,13 +559,6 @@ int interface_newindex_callback(lua_State *L) } } -int panic_msghandler(lua_State *L) -{ - size_t gostateindex = clua_getgostate(L); - go_panic_msghandler(gostateindex, (char *)lua_tolstring(L, -1, NULL)); - return 0; -} - void clua_hide_pcall(lua_State *L) { lua_getglobal(L, "pcall"); @@ -267,7 +609,6 @@ void clua_initstate(lua_State* L) lua_pop(L, 1); } - int callback_panicf(lua_State* L) { lua_pushlightuserdata(L,(void*)&PanicFIDRegistryKey); @@ -276,11 +617,10 @@ int callback_panicf(lua_State* L) lua_pop(L,1); size_t gostateindex = clua_getgostate(L); return golua_callpanicfunction(gostateindex,fid); - } //TODO: currently setting garbage when panicf set to null -GoInterface clua_atpanic(lua_State* L, unsigned int panicf_id) +GoValue clua_atpanic(lua_State* L, unsigned int panicf_id) { //get old panicfid unsigned int old_id; @@ -301,14 +641,9 @@ GoInterface clua_atpanic(lua_State* L, unsigned int panicf_id) lua_CFunction pf = lua_atpanic(L,&callback_panicf); //make a GoInterface with a wrapped C panicf or the original go panicf if(pf == &callback_panicf) - { - return golua_idtointerface(old_id); - } + return (GoValue){1, &old_id}; else - { - //TODO: technically UB, function ptr -> non function ptr - return golua_cfunctiontointerface((GoUintptr *)pf); - } + return (GoValue){2, pf}; } int clua_callluacfunc(lua_State* L, lua_CFunction f) @@ -339,6 +674,48 @@ void clua_openbase(lua_State* L) clua_hide_pcall(L); } +void clua_openio(lua_State* L) +{ + lua_pushcfunction(L,&luaopen_io); + lua_pushstring(L,"io"); + lua_call(L, 1, 0); +} + +void clua_openmath(lua_State* L) +{ + lua_pushcfunction(L,&luaopen_math); + lua_pushstring(L,"math"); + lua_call(L, 1, 0); +} + +void clua_openpackage(lua_State* L) +{ + lua_pushcfunction(L,&luaopen_package); + lua_pushstring(L,"package"); + lua_call(L, 1, 0); +} + +void clua_openstring(lua_State* L) +{ + lua_pushcfunction(L,&luaopen_string); + lua_pushstring(L,"string"); + lua_call(L, 1, 0); +} + +void clua_opentable(lua_State* L) +{ + lua_pushcfunction(L,&luaopen_table); + lua_pushstring(L,"table"); + lua_call(L, 1, 0); +} + +void clua_openos(lua_State* L) +{ + lua_pushcfunction(L,&luaopen_os); + lua_pushstring(L,"os"); + lua_call(L, 1, 0); +} + void clua_hook_function(lua_State *L, lua_Debug *ar) { lua_checkstack(L, 2); @@ -351,4 +728,74 @@ void clua_sethook(lua_State* L, int n) lua_sethook(L, &clua_hook_function, LUA_MASKCOUNT, n); } +/*return the ctype of the cdata at the top of the stack*/ +uint32_t clua_luajit_ctypeid(lua_State *L, int idx) +{ + return luajit_ctypeid(L, idx); +} +void clua_luajit_push_cdata_int64(lua_State *L, int64_t n) +{ + return luajit_push_cdata_int64(L, n); +} + +void clua_luajit_push_cdata_uint64(lua_State *L, uint64_t u) +{ + return luajit_push_cdata_uint64(L, u); +} + +typedef struct _chunk { + int size; // chunk size + char *buffer; // chunk data + char* toread; // chunk to read +} chunk; + +static const char * reader(lua_State *L, void *ud, size_t *sz) { + chunk *ck = (chunk *)ud; + if (ck->size > LUAL_BUFFERSIZE) { + ck->size -= LUAL_BUFFERSIZE; + *sz = LUAL_BUFFERSIZE; + ck->toread = ck->buffer; + ck->buffer += LUAL_BUFFERSIZE; + }else{ + *sz = ck->size; + ck->toread = ck->buffer; + ck->size = 0; + } + return ck->toread; +} + +static int writer(lua_State *L, const void* b, size_t size, void* B) { + static int count=0; + (void)L; + luaL_addlstring((luaL_Buffer*) B, (const char *)b, size); + return 0; +} + +// load function chunk dumped from dump_chunk +int load_chunk(lua_State *L, char *b, int size, const char* chunk_name) { + chunk ck; + ck.buffer = b; + ck.size = size; + int err; + err = lua_load(L, reader, &ck, chunk_name); + if (err != 0) { + return luaL_error(L, "unable to load chunk, err: %d", err); + } + return 0; +} + +// dump function chunk from luaL_loadstring +int dump_chunk(lua_State *L) { + luaL_Buffer b; + luaL_checktype(L, -1, LUA_TFUNCTION); + lua_settop(L, -1); + luaL_buffinit(L,&b); + int err; + err = lua_dump(L, writer, &b); + if (err != 0){ + return luaL_error(L, "unable to dump given function, err:%d", err); + } + luaL_pushresult(&b); + return 0; +} diff --git a/lua/dummy.go b/lua/dummy.go index 491fbb8..b2fbbc6 100644 --- a/lua/dummy.go +++ b/lua/dummy.go @@ -1,3 +1,4 @@ +//go:build dummy // +build dummy // This file is part of a workaround for `go mod vendor` which won't @@ -14,8 +15,5 @@ package lua import ( - _ "github.com/aarzilli/golua/lua/lua51" - _ "github.com/aarzilli/golua/lua/lua52" - _ "github.com/aarzilli/golua/lua/lua53" - _ "github.com/aarzilli/golua/lua/lua54" + _ "github.com/vxcontrol/golua/lua/lua" ) diff --git a/lua/golua.go b/lua/golua.go index ac59452..59cec56 100644 --- a/lua/golua.go +++ b/lua/golua.go @@ -1,14 +1,10 @@ package lua /* -#cgo !lua52,!lua53,!lua54 CFLAGS: -I ${SRCDIR}/lua51 -#cgo lua52 CFLAGS: -I ${SRCDIR}/lua52 -#cgo lua53 CFLAGS: -I ${SRCDIR}/lua53 -#cgo lua54 CFLAGS: -I ${SRCDIR}/lua54 +#cgo CFLAGS: -I ${SRCDIR} -I ${SRCDIR}/lua + +#include "golua.h" -#include -#include -#include */ import "C" @@ -16,6 +12,8 @@ import ( "reflect" "sync" "unsafe" + + "github.com/vxcontrol/rmx" ) // Type of allocation functions to use with NewStateAlloc @@ -36,14 +34,38 @@ type State struct { // Wrapped lua_State object s *C.lua_State + // Mutex for all C.lua* API + r *rmx.Mutex + // index of this object inside the goStates array - Index uintptr + Index int - // Registry of go object that have been pushed to Lua VM - registry []interface{} + Shared *SharedByAllCoroutines - // Freelist for funcs indices, to allow for freeing - freeIndices []uint + IsMainCoro bool // if true, then will be registered + + MainCo *State // always points to the main coroutine. + CmainCo *C.lua_State // always points to the main coroutine's C state. + + // Upos is position in uniqArray. Upos must be 1 for + // a main state because code in c-golua.c counts on this + // to lookup the main coroutine from a non-main + // coroutine. As happens naturally, that means the main + // coroutine must be registered first, before any + // other coroutines in that main state are + // generated/registered. + // + Upos int + + // Upos -> all coroutines within a main state. + // For non-main coroutines, AllCoro is a nil map. + // + // TODO: currently no hooks for garbage collection + // from the Lua side back to Go. So when Lua + // deletes a coroutine, we don't notice, and + // it stays in our maps (uniqArray, revUniq, Lmap) + // and on the Go side (AllCoro) forever, at the moment. + AllCoro map[int]*State // User self defined memory alloc func for the lua State allocfn *Alloc @@ -52,45 +74,98 @@ type State struct { hookFn HookFunction } -var goStates map[uintptr]*State +type SharedByAllCoroutines struct { + // Registry of go object that have been pushed to Lua VM + registry []interface{} + + // Freelist for funcs indices, to allow for freeing + freeIndices []uint +} + +func newSharedByAllCoroutines() *SharedByAllCoroutines { + return &SharedByAllCoroutines{ + registry: make([]interface{}, 0, 8), + freeIndices: make([]uint, 0, 8), + } +} + +var goStates map[int]*State var goStatesMutex sync.Mutex func init() { - goStates = make(map[uintptr]*State, 16) + goStates = make(map[int]*State, 16) } +var nextGoStateIndex int = 1 + func registerGoState(L *State) { goStatesMutex.Lock() defer goStatesMutex.Unlock() - L.Index = uintptr(unsafe.Pointer(L)) + + // This is dangerous: + // L.Index = uintptr(unsafe.Pointer(L)) + // Why? + // If the Go garbage + // collector ever does become a moving + // collector (and the Go team has reserved + // the right to make that happen), and + // it just happens to swap + // addresses of two distinct L, then we + // could get address reuse and this would + // over-write a previous pointer, unexpectedly deleting it. + // + // It is much simpler and safer just to use + // a counter that is incremented under the + // lock we now hold. Thus: + + L.Index = nextGoStateIndex + nextGoStateIndex++ goStates[L.Index] = L } func unregisterGoState(L *State) { goStatesMutex.Lock() defer goStatesMutex.Unlock() - delete(goStates, L.Index) + if L.Index > 0 { + delete(goStates, L.Index) + } } -func getGoState(gostateindex uintptr) *State { +func getGoState(gostateindex int) *State { goStatesMutex.Lock() defer goStatesMutex.Unlock() return goStates[gostateindex] } //export golua_callgofunction -func golua_callgofunction(gostateindex uintptr, fid uint) int { - L1 := getGoState(gostateindex) - if fid < 0 { - panic(&LuaError{0, "Requested execution of an unknown function", L1.StackTrace()}) +func golua_callgofunction(coro *C.lua_State, coro_index uintptr, mainIndex uintptr, mainThread *C.lua_State, fid int) int { + var L1 *State + if coro_index == 0 { + // lua side created goroutine, first time seen; + // and not yet registered on the go-side. + + L := getGoState(int(mainIndex)) + if mainThread != nil && L.s != mainThread { + panic("mainThread pointers disaggree") + } + L1 = L.ToThreadHelper(coro) + } else { + // this is the __call() for the MT_GOFUNCTION + L1 = getGoState(int(coro_index)) } - f := L1.registry[fid].(LuaGoFunction) + + if fid < 0 { + L1.RaiseError("Requested execution of an unknown function") + return 1 + } + f := L1.Shared.registry[fid].(LuaGoFunction) + return f(L1) } //export golua_callgohook func golua_callgohook(gostateindex uintptr) { - L1 := getGoState(gostateindex) + L1 := getGoState(int(gostateindex)) if L1.hookFn != nil { L1.hookFn(L1) } @@ -99,9 +174,10 @@ func golua_callgohook(gostateindex uintptr) { var typeOfBytes = reflect.TypeOf([]byte(nil)) //export golua_interface_newindex_callback -func golua_interface_newindex_callback(gostateindex uintptr, iid uint, field_name_cstr *C.char) int { - L := getGoState(gostateindex) - iface := L.registry[iid] +func golua_interface_newindex_callback(coro *C.lua_State, mainIndex uintptr, iid uint, field_name_cstr *C.char) int { + L := getGoState(int(mainIndex)) + L1 := L.ToThreadHelper(coro) + iface := L.Shared.registry[iid] ifacevalue := reflect.ValueOf(iface).Elem() field_name := C.GoString(field_name_cstr) @@ -112,15 +188,15 @@ func golua_interface_newindex_callback(gostateindex uintptr, iid uint, field_nam fval = fval.Elem() } - luatype := LuaValType(C.lua_type(L.s, 3)) + luatype := L1.Type(3) switch fval.Kind() { case reflect.Bool: if luatype == LUA_TBOOLEAN { - fval.SetBool(int(C.lua_toboolean(L.s, 3)) != 0) + fval.SetBool(L1.ToBoolean(3)) return 1 } else { - L.PushString("Wrong assignment to field " + field_name) + L1.PushString("Wrong assignment to field " + field_name) return -1 } @@ -134,10 +210,10 @@ func golua_interface_newindex_callback(gostateindex uintptr, iid uint, field_nam fallthrough case reflect.Int64: if luatype == LUA_TNUMBER { - fval.SetInt(int64(luaToInteger(L.s, 3))) + fval.SetInt(L1.ToInteger64(3)) return 1 } else { - L.PushString("Wrong assignment to field " + field_name) + L1.PushString("Wrong assignment to field " + field_name) return -1 } @@ -151,19 +227,19 @@ func golua_interface_newindex_callback(gostateindex uintptr, iid uint, field_nam fallthrough case reflect.Uint64: if luatype == LUA_TNUMBER { - fval.SetUint(uint64(luaToInteger(L.s, 3))) + fval.SetUint(L1.ToUInteger64(3)) return 1 } else { - L.PushString("Wrong assignment to field " + field_name) + L1.PushString("Wrong assignment to field " + field_name) return -1 } case reflect.String: if luatype == LUA_TSTRING { - fval.SetString(C.GoString(C.lua_tolstring(L.s, 3, nil))) + fval.SetString(L1.ToString(3)) return 1 } else { - L.PushString("Wrong assignment to field " + field_name) + L1.PushString("Wrong assignment to field " + field_name) return -1 } @@ -171,32 +247,33 @@ func golua_interface_newindex_callback(gostateindex uintptr, iid uint, field_nam fallthrough case reflect.Float64: if luatype == LUA_TNUMBER { - fval.SetFloat(float64(luaToNumber(L.s, 3))) + fval.SetFloat(L1.ToFloat64(3)) return 1 } else { - L.PushString("Wrong assignment to field " + field_name) + L1.PushString("Wrong assignment to field " + field_name) return -1 } case reflect.Slice: if fval.Type() == typeOfBytes { if luatype == LUA_TSTRING { - fval.SetBytes(L.ToBytes(3)) + fval.SetBytes(L1.ToBytes(3)) return 1 } else { - L.PushString("Wrong assignment to field " + field_name) + L1.PushString("Wrong assignment to field " + field_name) return -1 } } } - L.PushString("Unsupported type of field " + field_name + ": " + fval.Type().String()) + L1.PushString("Unsupported type of field " + field_name + ": " + fval.Type().String()) return -1 } //export golua_interface_index_callback -func golua_interface_index_callback(gostateindex uintptr, iid uint, field_name *C.char) int { - L := getGoState(gostateindex) - iface := L.registry[iid] +func golua_interface_index_callback(coro *C.lua_State, mainIndex uintptr, iid uint, field_name *C.char) int { + L := getGoState(int(mainIndex)) + L1 := L.ToThreadHelper(coro) + iface := L1.Shared.registry[iid] ifacevalue := reflect.ValueOf(iface).Elem() fval := ifacevalue.FieldByName(C.GoString(field_name)) @@ -207,7 +284,7 @@ func golua_interface_index_callback(gostateindex uintptr, iid uint, field_name * switch fval.Kind() { case reflect.Bool: - L.PushBoolean(fval.Bool()) + L1.PushBoolean(fval.Bool()) return 1 case reflect.Int: @@ -219,7 +296,7 @@ func golua_interface_index_callback(gostateindex uintptr, iid uint, field_name * case reflect.Int32: fallthrough case reflect.Int64: - L.PushInteger(fval.Int()) + L1.PushInteger(fval.Int()) return 1 case reflect.Uint: @@ -231,62 +308,60 @@ func golua_interface_index_callback(gostateindex uintptr, iid uint, field_name * case reflect.Uint32: fallthrough case reflect.Uint64: - L.PushInteger(int64(fval.Uint())) + L1.PushInteger(int64(fval.Uint())) return 1 case reflect.String: - L.PushString(fval.String()) + L1.PushString(fval.String()) return 1 case reflect.Float32: fallthrough case reflect.Float64: - L.PushNumber(fval.Float()) + L1.PushNumber(fval.Float()) return 1 case reflect.Slice: if fval.Type() == typeOfBytes { - L.PushBytes(fval.Bytes()) + L1.PushBytes(fval.Bytes()) return 1 } } - L.PushString("Unsupported type of field: " + fval.Type().String()) + L1.PushString("Unsupported type of field: " + fval.Type().String()) return -1 } //export golua_gchook -func golua_gchook(gostateindex uintptr, id uint) int { - L1 := getGoState(gostateindex) - L1.unregister(id) +func golua_gchook(main_index uintptr, id uint) int { + L := getGoState(int(main_index)) + L.unregister(id) return 0 } //export golua_callpanicfunction func golua_callpanicfunction(gostateindex uintptr, id uint) int { - L1 := getGoState(gostateindex) - f := L1.registry[id].(LuaGoFunction) + L1 := getGoState(int(gostateindex)) + f := L1.Shared.registry[id].(LuaGoFunction) return f(L1) } -//export golua_idtointerface -func golua_idtointerface(id uint) interface{} { - return id -} - -//export golua_cfunctiontointerface -func golua_cfunctiontointerface(f *uintptr) interface{} { - return f -} - //export golua_callallocf func golua_callallocf(fp uintptr, ptr uintptr, osize uint, nsize uint) uintptr { return uintptr((*((*Alloc)(unsafe.Pointer(fp))))(unsafe.Pointer(ptr), osize, nsize)) } //export go_panic_msghandler -func go_panic_msghandler(gostateindex uintptr, z *C.char) { - L := getGoState(gostateindex) - s := C.GoString(z) - - panic(&LuaError{LUA_ERRERR, s, L.StackTrace()}) +func go_panic_msghandler(coro *C.lua_State, mainIndex uintptr, z *C.char) { + L := getGoState(int(mainIndex)) + L1 := L.ToThreadHelper(coro) + L1.Pop(-1) + L1.PushString((&LuaError{}).New(L1, LUA_ERRRUN, C.GoString(z)).String()) +} + +//export go_default_panic_msghandler +func go_default_panic_msghandler(coro *C.lua_State, mainIndex uintptr, z *C.char) { + L := getGoState(int(mainIndex)) + L1 := L.ToThreadHelper(coro) + le := &LuaError{} + panic(le.New(L1, LUA_ERRERR, C.GoString(z))) } diff --git a/lua/golua.h b/lua/golua.h index 667e1ab..aeb7ee3 100644 --- a/lua/golua.h +++ b/lua/golua.h @@ -1,6 +1,16 @@ +#include "lua/lua.h" +#include "lua/lauxlib.h" +#include "lua/lualib.h" +#define LJ_HASFFI 1 +#include "lua/luajit-ffi-ctypeid.h" #include +#include // _atoi64 on windows, atoll on posix. +#include -typedef struct { void *t; void *v; } GoInterface; +#ifndef golua_h +#define golua_h + +typedef struct { int t; void *v; } GoValue; #define GOLUA_DEFAULT_MSGHANDLER "golua_default_msghandler" @@ -8,19 +18,24 @@ typedef struct { void *t; void *v; } GoInterface; void clua_initstate(lua_State* L); void clua_hide_pcall(lua_State *L); -unsigned int clua_togofunction(lua_State* L, int index); -unsigned int clua_togostruct(lua_State *L, int index); +lua_State* clua_newstate(void* goallocf); +int clua_setgostate(lua_State* L, size_t gostateindex); +size_t clua_getgostate(lua_State* L); + +int clua_togofunction(lua_State* L, int index); +int clua_togostruct(lua_State *L, int index); + void clua_pushcallback(lua_State* L); void clua_pushgofunction(lua_State* L, unsigned int fid); void clua_pushgostruct(lua_State *L, unsigned int fid); -void clua_setgostate(lua_State* L, size_t gostateindex); + int dump_chunk (lua_State *L); -int load_chunk(lua_State *L, const char *b, int size, const char* chunk_name); -size_t clua_getgostate(lua_State* L); -GoInterface clua_atpanic(lua_State* L, unsigned int panicf_id); +int load_chunk(lua_State *L, char *b, int size, const char* chunk_name); +GoValue clua_atpanic(lua_State* L, unsigned int panicf_id); int clua_callluacfunc(lua_State* L, lua_CFunction f); -lua_State* clua_newstate(void* goallocf); + void clua_setallocf(lua_State* L, void* goallocf); +void clua_sethook(lua_State* L, int n); void clua_openbase(lua_State* L); void clua_openio(lua_State* L); @@ -29,8 +44,21 @@ void clua_openpackage(lua_State* L); void clua_openstring(lua_State* L); void clua_opentable(lua_State* L); void clua_openos(lua_State* L); -void clua_sethook(lua_State* L, int n); + +uint32_t clua_luajit_ctypeid(lua_State *L, int idx); +void clua_luajit_push_cdata_int64(lua_State *L, int64_t n); +void clua_luajit_push_cdata_uint64(lua_State *L, uint64_t u); int clua_isgofunction(lua_State *L, int n); int clua_isgostruct(lua_State *L, int n); +int clua_create_uniqArrayIfNotExists(lua_State* L); +int clua_dedup_coro(lua_State* coro); + +// return upos, the array index into uniqArray for coro. +int clua_addThreadToUniqArrayAndRevUniq(lua_State* L); + +void bundle_add_loaders(lua_State* L); +int bundle_main(lua_State *L, int argc, char** argv); + +#endif diff --git a/lua/golua_c_lua51.go b/lua/golua_c_lua51.go deleted file mode 100644 index 4b59d4c..0000000 --- a/lua/golua_c_lua51.go +++ /dev/null @@ -1,209 +0,0 @@ -//+build !lua52,!lua53,!lua54 - -package lua - -/* -#include -#include -#include -#include - -typedef struct _chunk { - int size; // chunk size - char *buffer; // chunk data - char* toread; // chunk to read -} chunk; - -static const char * reader (lua_State *L, void *ud, size_t *sz) { - chunk *ck = (chunk *)ud; - if (ck->size > LUAL_BUFFERSIZE) { - ck->size -= LUAL_BUFFERSIZE; - *sz = LUAL_BUFFERSIZE; - ck->toread = ck->buffer; - ck->buffer += LUAL_BUFFERSIZE; - }else{ - *sz = ck->size; - ck->toread = ck->buffer; - ck->size = 0; - } - return ck->toread; -} - -static int writer (lua_State *L, const void* b, size_t size, void* B) { - static int count=0; - (void)L; - luaL_addlstring((luaL_Buffer*) B, (const char *)b, size); - return 0; -} - -// load function chunk dumped from dump_chunk -int load_chunk(lua_State *L, char *b, int size, const char* chunk_name) { - chunk ck; - ck.buffer = b; - ck.size = size; - int err; - err = lua_load(L, reader, &ck, chunk_name); - if (err != 0) { - return luaL_error(L, "unable to load chunk, err: %d", err); - } - return 0; -} - -void clua_openio(lua_State* L) -{ - lua_pushcfunction(L,&luaopen_io); - lua_pushstring(L,"io"); - lua_call(L, 1, 0); -} - -void clua_openmath(lua_State* L) -{ - lua_pushcfunction(L,&luaopen_math); - lua_pushstring(L,"math"); - lua_call(L, 1, 0); -} - -void clua_openpackage(lua_State* L) -{ - lua_pushcfunction(L,&luaopen_package); - lua_pushstring(L,"package"); - lua_call(L, 1, 0); -} - -void clua_openstring(lua_State* L) -{ - lua_pushcfunction(L,&luaopen_string); - lua_pushstring(L,"string"); - lua_call(L, 1, 0); -} - -void clua_opentable(lua_State* L) -{ - lua_pushcfunction(L,&luaopen_table); - lua_pushstring(L,"table"); - lua_call(L, 1, 0); -} - -void clua_openos(lua_State* L) -{ - lua_pushcfunction(L,&luaopen_os); - lua_pushstring(L,"os"); - lua_call(L, 1, 0); -} - -// dump function chunk from luaL_loadstring -int dump_chunk (lua_State *L) { - luaL_Buffer b; - luaL_checktype(L, -1, LUA_TFUNCTION); - lua_settop(L, -1); - luaL_buffinit(L,&b); - int err; - err = lua_dump(L, writer, &b); - if (err != 0){ - return luaL_error(L, "unable to dump given function, err:%d", err); - } - luaL_pushresult(&b); - return 0; -} -*/ -import "C" - -import "unsafe" - -func luaToInteger(s *C.lua_State, n C.int) C.long { - return C.lua_tointeger(s, n) -} - -func luaToNumber(s *C.lua_State, n C.int) C.double { - return C.lua_tonumber(s, n) -} - -func lualLoadFile(s *C.lua_State, filename *C.char) C.int { - return C.luaL_loadfile(s, filename) -} - -// lua_equal -func (L *State) Equal(index1, index2 int) bool { - return C.lua_equal(L.s, C.int(index1), C.int(index2)) == 1 -} - -// lua_getfenv -func (L *State) GetfEnv(index int) { - C.lua_getfenv(L.s, C.int(index)) -} - -// lua_lessthan -func (L *State) LessThan(index1, index2 int) bool { - return C.lua_lessthan(L.s, C.int(index1), C.int(index2)) == 1 -} - -// lua_setfenv -func (L *State) SetfEnv(index int) { - C.lua_setfenv(L.s, C.int(index)) -} - -func (L *State) ObjLen(index int) uint { - return uint(C.lua_objlen(L.s, C.int(index))) -} - -// lua_tointeger -func (L *State) ToInteger(index int) int { - return int(C.lua_tointeger(L.s, C.int(index))) -} - -// lua_tonumber -func (L *State) ToNumber(index int) float64 { - return float64(C.lua_tonumber(L.s, C.int(index))) -} - -// lua_yield -func (L *State) Yield(nresults int) int { - return int(C.lua_yield(L.s, C.int(nresults))) -} - -func (L *State) pcall(nargs, nresults, errfunc int) int { - return int(C.lua_pcall(L.s, C.int(nargs), C.int(nresults), C.int(errfunc))) -} - -// Pushes on the stack the value of a global variable (lua_getglobal) -func (L *State) GetGlobal(name string) { L.GetField(LUA_GLOBALSINDEX, name) } - -// lua_resume -func (L *State) Resume(narg int) int { - return int(C.lua_resume(L.s, C.int(narg))) -} - -// lua_setglobal -func (L *State) SetGlobal(name string) { - Cname := C.CString(name) - defer C.free(unsafe.Pointer(Cname)) - C.lua_setfield(L.s, C.int(LUA_GLOBALSINDEX), Cname) -} - -// lua_insert -func (L *State) Insert(index int) { C.lua_insert(L.s, C.int(index)) } - -// lua_remove -func (L *State) Remove(index int) { - C.lua_remove(L.s, C.int(index)) -} - -// lua_replace -func (L *State) Replace(index int) { - C.lua_replace(L.s, C.int(index)) -} - -// lua_rawgeti -func (L *State) RawGeti(index int, n int) { - C.lua_rawgeti(L.s, C.int(index), C.int(n)) -} - -// lua_rawseti -func (L *State) RawSeti(index int, n int) { - C.lua_rawseti(L.s, C.int(index), C.int(n)) -} - -// lua_gc -func (L *State) GC(what, data int) int { - return int(C.lua_gc(L.s, C.int(what), C.int(data))) -} diff --git a/lua/golua_c_lua52.go b/lua/golua_c_lua52.go deleted file mode 100644 index a792ccd..0000000 --- a/lua/golua_c_lua52.go +++ /dev/null @@ -1,230 +0,0 @@ -//+build lua52 - -package lua - -/* -#include -#include -#include -#include - -typedef struct _chunk { - int size; // chunk size - char *buffer; // chunk data - char* toread; // chunk to read -} chunk; - -static const char * reader (lua_State *L, void *ud, size_t *sz) { - chunk *ck = (chunk *)ud; - if (ck->size > LUAL_BUFFERSIZE) { - ck->size -= LUAL_BUFFERSIZE; - *sz = LUAL_BUFFERSIZE; - ck->toread = ck->buffer; - ck->buffer += LUAL_BUFFERSIZE; - }else{ - *sz = ck->size; - ck->toread = ck->buffer; - ck->size = 0; - } - return ck->toread; -} - -static int writer (lua_State *L, const void* b, size_t size, void* B) { - static int count=0; - (void)L; - luaL_addlstring((luaL_Buffer*) B, (const char *)b, size); - return 0; -} - -// load function chunk dumped from dump_chunk -int load_chunk(lua_State *L, char *b, int size, const char* chunk_name) { - chunk ck; - ck.buffer = b; - ck.size = size; - int err; - err = lua_load(L, reader, &ck, chunk_name, NULL); - if (err != 0) { - return luaL_error(L, "unable to load chunk, err: %d", err); - } - return 0; -} - -void clua_openio(lua_State* L) -{ - luaL_requiref(L, "io", &luaopen_io, 1); - lua_pop(L, 1); -} - -void clua_openmath(lua_State* L) -{ - luaL_requiref(L, "math", &luaopen_math, 1); - lua_pop(L, 1); -} - -void clua_openpackage(lua_State* L) -{ - luaL_requiref(L, "package", &luaopen_package, 1); - lua_pop(L, 1); -} - -void clua_openstring(lua_State* L) -{ - luaL_requiref(L, "string", &luaopen_string, 1); - lua_pop(L, 1); -} - -void clua_opentable(lua_State* L) -{ - luaL_requiref(L, "table", &luaopen_table, 1); - lua_pop(L, 1); -} - -void clua_openos(lua_State* L) -{ - luaL_requiref(L, "os", &luaopen_os, 1); - lua_pop(L, 1); -} - -void clua_opencoroutine(lua_State *L) -{ - luaL_requiref(L, "coroutine", &luaopen_coroutine, 1); - lua_pop(L, 1); -} - -void clua_opendebug(lua_State *L) -{ - luaL_requiref(L, "debug", &luaopen_debug, 1); - lua_pop(L, 1); -} - -void clua_openbit32(lua_State *L) -{ - luaL_requiref(L, "bit32", &luaopen_bit32, 1); - lua_pop(L, 1); -} - -// dump function chunk from luaL_loadstring -int dump_chunk (lua_State *L) { - luaL_Buffer b; - luaL_checktype(L, -1, LUA_TFUNCTION); - lua_settop(L, -1); - luaL_buffinit(L,&b); - int err; - err = lua_dump(L, writer, &b); - if (err != 0){ - return luaL_error(L, "unable to dump given function, err:%d", err); - } - luaL_pushresult(&b); - return 0; -} -*/ -import "C" - -import "unsafe" - -func luaToInteger(s *C.lua_State, n C.int) C.long { - return C.lua_tointegerx(s, n, nil) -} - -func luaToNumber(s *C.lua_State, n C.int) C.double { - return C.lua_tonumberx(s, n, nil) -} - -func lualLoadFile(s *C.lua_State, filename *C.char) C.int { - return C.luaL_loadfilex(s, filename, nil) -} - -// lua_equal -func (L *State) Equal(index1, index2 int) bool { - return C.lua_compare(L.s, C.int(index1), C.int(index2), C.LUA_OPEQ) == 1 -} - -// lua_lessthan -func (L *State) LessThan(index1, index2 int) bool { - return C.lua_compare(L.s, C.int(index1), C.int(index2), C.LUA_OPLT) == 1 -} - -func (L *State) ObjLen(index int) uint { - return uint(C.lua_rawlen(L.s, C.int(index))) -} - -// lua_tointeger -func (L *State) ToInteger(index int) int { - return int(C.lua_tointegerx(L.s, C.int(index), nil)) -} - -// lua_tonumber -func (L *State) ToNumber(index int) float64 { - return float64(C.lua_tonumberx(L.s, C.int(index), nil)) -} - -// lua_yield -func (L *State) Yield(nresults int) int { - return int(C.lua_yieldk(L.s, C.int(nresults), 0, nil)) -} - -func (L *State) pcall(nargs, nresults, errfunc int) int { - return int(C.lua_pcallk(L.s, C.int(nargs), C.int(nresults), C.int(errfunc), 0, nil)) -} - -// Pushes on the stack the value of a global variable (lua_getglobal) -func (L *State) GetGlobal(name string) { - Ck := C.CString(name) - defer C.free(unsafe.Pointer(Ck)) - C.lua_getglobal(L.s, Ck) -} - -// lua_resume -func (L *State) Resume(narg int) int { - return int(C.lua_resume(L.s, nil, C.int(narg))) -} - -// lua_setglobal -func (L *State) SetGlobal(name string) { - Cname := C.CString(name) - defer C.free(unsafe.Pointer(Cname)) - C.lua_setglobal(L.s, Cname) -} - -// Calls luaopen_debug -func (L *State) OpenDebug() { - C.clua_opendebug(L.s) -} - -// Calls luaopen_bit32 -func (L *State) OpenBit32() { - C.clua_openbit32(L.s) -} - -// Calls luaopen_coroutine -func (L *State) OpenCoroutine() { - C.clua_opencoroutine(L.s) -} - -// lua_insert -func (L *State) Insert(index int) { C.lua_insert(L.s, C.int(index)) } - -// lua_remove -func (L *State) Remove(index int) { - C.lua_remove(L.s, C.int(index)) -} - -// lua_replace -func (L *State) Replace(index int) { - C.lua_replace(L.s, C.int(index)) -} - -// lua_rawgeti -func (L *State) RawGeti(index int, n int) { - C.lua_rawgeti(L.s, C.int(index), C.int(n)) -} - -// lua_rawseti -func (L *State) RawSeti(index int, n int) { - C.lua_rawseti(L.s, C.int(index), C.int(n)) -} - -// lua_gc -func (L *State) GC(what, data int) int { - return int(C.lua_gc(L.s, C.int(what), C.int(data))) -} diff --git a/lua/golua_c_lua53.go b/lua/golua_c_lua53.go deleted file mode 100644 index d490b1b..0000000 --- a/lua/golua_c_lua53.go +++ /dev/null @@ -1,232 +0,0 @@ -//+build lua53 - -package lua - -/* -#include -#include -#include -#include - -typedef struct _chunk { - int size; // chunk size - char *buffer; // chunk data - char* toread; // chunk to read -} chunk; - -static const char * reader (lua_State *L, void *ud, size_t *sz) { - chunk *ck = (chunk *)ud; - if (ck->size > LUAL_BUFFERSIZE) { - ck->size -= LUAL_BUFFERSIZE; - *sz = LUAL_BUFFERSIZE; - ck->toread = ck->buffer; - ck->buffer += LUAL_BUFFERSIZE; - }else{ - *sz = ck->size; - ck->toread = ck->buffer; - ck->size = 0; - } - return ck->toread; -} - -static int writer (lua_State *L, const void* b, size_t size, void* B) { - static int count=0; - (void)L; - luaL_addlstring((luaL_Buffer*) B, (const char *)b, size); - return 0; -} - -// load function chunk dumped from dump_chunk -int load_chunk(lua_State *L, char *b, int size, const char* chunk_name) { - chunk ck; - ck.buffer = b; - ck.size = size; - int err; - err = lua_load(L, reader, &ck, chunk_name, NULL); - if (err != 0) { - return luaL_error(L, "unable to load chunk, err: %d", err); - } - return 0; -} - -void clua_openio(lua_State* L) -{ - luaL_requiref(L, "io", &luaopen_io, 1); - lua_pop(L, 1); -} - -void clua_openmath(lua_State* L) -{ - luaL_requiref(L, "math", &luaopen_math, 1); - lua_pop(L, 1); -} - -void clua_openpackage(lua_State* L) -{ - luaL_requiref(L, "package", &luaopen_package, 1); - lua_pop(L, 1); -} - -void clua_openstring(lua_State* L) -{ - luaL_requiref(L, "string", &luaopen_string, 1); - lua_pop(L, 1); -} - -void clua_opentable(lua_State* L) -{ - luaL_requiref(L, "table", &luaopen_table, 1); - lua_pop(L, 1); -} - -void clua_openos(lua_State* L) -{ - luaL_requiref(L, "os", &luaopen_os, 1); - lua_pop(L, 1); -} - -void clua_opencoroutine(lua_State *L) -{ - luaL_requiref(L, "coroutine", &luaopen_coroutine, 1); - lua_pop(L, 1); -} - -void clua_opendebug(lua_State *L) -{ - luaL_requiref(L, "debug", &luaopen_debug, 1); - lua_pop(L, 1); -} - -void clua_openbit32(lua_State *L) -{ - luaL_requiref(L, "bit32", &luaopen_bit32, 1); - lua_pop(L, 1); -} - -// dump function chunk from luaL_loadstring -int dump_chunk (lua_State *L) { - luaL_Buffer b; - luaL_checktype(L, -1, LUA_TFUNCTION); - lua_settop(L, -1); - luaL_buffinit(L,&b); - int err; - err = lua_dump(L, writer, &b, 0); - if (err != 0){ - return luaL_error(L, "unable to dump given function, err:%d", err); - } - luaL_pushresult(&b); - return 0; -} -*/ -import "C" - -import "unsafe" - -func luaToInteger(s *C.lua_State, n C.int) C.longlong { - return C.lua_tointegerx(s, n, nil) -} - -func luaToNumber(s *C.lua_State, n C.int) C.double { - return C.lua_tonumberx(s, n, nil) -} - -func lualLoadFile(s *C.lua_State, filename *C.char) C.int { - return C.luaL_loadfilex(s, filename, nil) -} - -// lua_equal -func (L *State) Equal(index1, index2 int) bool { - return C.lua_compare(L.s, C.int(index1), C.int(index2), C.LUA_OPEQ) == 1 -} - -// lua_lessthan -func (L *State) LessThan(index1, index2 int) bool { - return C.lua_compare(L.s, C.int(index1), C.int(index2), C.LUA_OPLT) == 1 -} - -func (L *State) ObjLen(index int) uint { - return uint(C.lua_rawlen(L.s, C.int(index))) -} - -// lua_tointeger -func (L *State) ToInteger(index int) int { - return int(C.lua_tointegerx(L.s, C.int(index), nil)) -} - -// lua_tonumber -func (L *State) ToNumber(index int) float64 { - return float64(C.lua_tonumberx(L.s, C.int(index), nil)) -} - -// lua_yield -func (L *State) Yield(nresults int) int { - return int(C.lua_yieldk(L.s, C.int(nresults), 0, nil)) -} - -func (L *State) pcall(nargs, nresults, errfunc int) int { - return int(C.lua_pcallk(L.s, C.int(nargs), C.int(nresults), C.int(errfunc), 0, nil)) -} - -// Pushes on the stack the value of a global variable (lua_getglobal) -func (L *State) GetGlobal(name string) { - Ck := C.CString(name) - defer C.free(unsafe.Pointer(Ck)) - C.lua_getglobal(L.s, Ck) -} - -// lua_resume -func (L *State) Resume(narg int) int { - return int(C.lua_resume(L.s, nil, C.int(narg))) -} - -// lua_setglobal -func (L *State) SetGlobal(name string) { - Cname := C.CString(name) - defer C.free(unsafe.Pointer(Cname)) - C.lua_setglobal(L.s, Cname) -} - -// Calls luaopen_debug -func (L *State) OpenDebug() { - C.clua_opendebug(L.s) -} - -// Calls luaopen_bit32 -func (L *State) OpenBit32() { - C.clua_openbit32(L.s) -} - -// Calls luaopen_coroutine -func (L *State) OpenCoroutine() { - C.clua_opencoroutine(L.s) -} - -// lua_insert -func (L *State) Insert(index int) { C.lua_rotate(L.s, C.int(index), 1) } - -// lua_remove -func (L *State) Remove(index int) { - C.lua_rotate(L.s, C.int(index), -1) - C.lua_settop(L.s, C.int(-2)) -} - -// lua_replace -func (L *State) Replace(index int) { - C.lua_copy(L.s, -1, C.int(index)) - C.lua_settop(L.s, -2) -} - -// lua_rawgeti -func (L *State) RawGeti(index int, n int) { - C.lua_rawgeti(L.s, C.int(index), C.longlong(n)) -} - -// lua_rawseti -func (L *State) RawSeti(index int, n int) { - C.lua_rawseti(L.s, C.int(index), C.longlong(n)) -} - -// lua_gc -func (L *State) GC(what, data int) int { - return int(C.lua_gc(L.s, C.int(what), C.int(data))) -} diff --git a/lua/golua_c_lua54.go b/lua/golua_c_lua54.go deleted file mode 100644 index 9acafe5..0000000 --- a/lua/golua_c_lua54.go +++ /dev/null @@ -1,229 +0,0 @@ -//+build lua54 - -package lua - -/* -#include -#include -#include -#include - -typedef struct _chunk { - int size; // chunk size - char *buffer; // chunk data - char* toread; // chunk to read -} chunk; - -LUA_API void *lua_newuserdata (lua_State *L, size_t size) { - return lua_newuserdatauv(L, size, 1); -} - -LUA_API int (lua_gc_compat) (lua_State *L, int what, int data) { - return lua_gc(L, what, data); -} - -static const char * reader (lua_State *L, void *ud, size_t *sz) { - chunk *ck = (chunk *)ud; - if (ck->size > LUAL_BUFFERSIZE) { - ck->size -= LUAL_BUFFERSIZE; - *sz = LUAL_BUFFERSIZE; - ck->toread = ck->buffer; - ck->buffer += LUAL_BUFFERSIZE; - }else{ - *sz = ck->size; - ck->toread = ck->buffer; - ck->size = 0; - } - return ck->toread; -} - -static int writer (lua_State *L, const void* b, size_t size, void* B) { - static int count=0; - (void)L; - luaL_addlstring((luaL_Buffer*) B, (const char *)b, size); - return 0; -} - -// load function chunk dumped from dump_chunk -int load_chunk(lua_State *L, char *b, int size, const char* chunk_name) { - chunk ck; - ck.buffer = b; - ck.size = size; - int err; - err = lua_load(L, reader, &ck, chunk_name, NULL); - if (err != 0) { - return luaL_error(L, "unable to load chunk, err: %d", err); - } - return 0; -} - -void clua_openio(lua_State* L) -{ - luaL_requiref(L, "io", &luaopen_io, 1); - lua_pop(L, 1); -} - -void clua_openmath(lua_State* L) -{ - luaL_requiref(L, "math", &luaopen_math, 1); - lua_pop(L, 1); -} - -void clua_openpackage(lua_State* L) -{ - luaL_requiref(L, "package", &luaopen_package, 1); - lua_pop(L, 1); -} - -void clua_openstring(lua_State* L) -{ - luaL_requiref(L, "string", &luaopen_string, 1); - lua_pop(L, 1); -} - -void clua_opentable(lua_State* L) -{ - luaL_requiref(L, "table", &luaopen_table, 1); - lua_pop(L, 1); -} - -void clua_openos(lua_State* L) -{ - luaL_requiref(L, "os", &luaopen_os, 1); - lua_pop(L, 1); -} - -void clua_opencoroutine(lua_State *L) -{ - luaL_requiref(L, "coroutine", &luaopen_coroutine, 1); - lua_pop(L, 1); -} - -void clua_opendebug(lua_State *L) -{ - luaL_requiref(L, "debug", &luaopen_debug, 1); - lua_pop(L, 1); -} - -// dump function chunk from luaL_loadstring -int dump_chunk (lua_State *L) { - luaL_Buffer b; - luaL_checktype(L, -1, LUA_TFUNCTION); - lua_settop(L, -1); - luaL_buffinit(L,&b); - int err; - err = lua_dump(L, writer, &b, 0); - if (err != 0){ - return luaL_error(L, "unable to dump given function, err:%d", err); - } - luaL_pushresult(&b); - return 0; -} -*/ -import "C" - -import "unsafe" - -func luaToInteger(s *C.lua_State, n C.int) C.longlong { - return C.lua_tointegerx(s, n, nil) -} - -func luaToNumber(s *C.lua_State, n C.int) C.double { - return C.lua_tonumberx(s, n, nil) -} - -func lualLoadFile(s *C.lua_State, filename *C.char) C.int { - return C.luaL_loadfilex(s, filename, nil) -} - -// lua_equal -func (L *State) Equal(index1, index2 int) bool { - return C.lua_compare(L.s, C.int(index1), C.int(index2), C.LUA_OPEQ) == 1 -} - -// lua_lessthan -func (L *State) LessThan(index1, index2 int) bool { - return C.lua_compare(L.s, C.int(index1), C.int(index2), C.LUA_OPLT) == 1 -} - -func (L *State) ObjLen(index int) uint { - return uint(C.lua_rawlen(L.s, C.int(index))) -} - -// lua_tointeger -func (L *State) ToInteger(index int) int { - return int(C.lua_tointegerx(L.s, C.int(index), nil)) -} - -// lua_tonumber -func (L *State) ToNumber(index int) float64 { - return float64(C.lua_tonumberx(L.s, C.int(index), nil)) -} - -// lua_yield -func (L *State) Yield(nresults int) int { - return int(C.lua_yieldk(L.s, C.int(nresults), 0, nil)) -} - -func (L *State) pcall(nargs, nresults, errfunc int) int { - return int(C.lua_pcallk(L.s, C.int(nargs), C.int(nresults), C.int(errfunc), 0, nil)) -} - -// Pushes on the stack the value of a global variable (lua_getglobal) -func (L *State) GetGlobal(name string) { - Ck := C.CString(name) - defer C.free(unsafe.Pointer(Ck)) - C.lua_getglobal(L.s, Ck) -} - -// lua_resume -func (L *State) Resume(narg int) int { - return int(C.lua_resume(L.s, nil, C.int(narg), nil)) -} - -// lua_setglobal -func (L *State) SetGlobal(name string) { - Cname := C.CString(name) - defer C.free(unsafe.Pointer(Cname)) - C.lua_setglobal(L.s, Cname) -} - -// Calls luaopen_debug -func (L *State) OpenDebug() { - C.clua_opendebug(L.s) -} - -// Calls luaopen_coroutine -func (L *State) OpenCoroutine() { - C.clua_opencoroutine(L.s) -} - -// lua_insert -func (L *State) Insert(index int) { C.lua_rotate(L.s, C.int(index), 1) } - -// lua_remove -func (L *State) Remove(index int) { - C.lua_rotate(L.s, C.int(index), -1) - C.lua_settop(L.s, C.int(-2)) -} - -// lua_replace -func (L *State) Replace(index int) { - C.lua_copy(L.s, -1, C.int(index)) - C.lua_settop(L.s, -2) -} - -// lua_rawgeti -func (L *State) RawGeti(index int, n int) { - C.lua_rawgeti(L.s, C.int(index), C.longlong(n)) -} - -// lua_rawseti -func (L *State) RawSeti(index int, n int) { - C.lua_rawseti(L.s, C.int(index), C.longlong(n)) -} - -// lua_gc -func (L *State) GC(what, data int) int { - return int(C.lua_gc_compat(L.s, C.int(what), C.int(data))) -} diff --git a/lua/lauxlib.go b/lua/lauxlib.go index 343da92..fc29729 100644 --- a/lua/lauxlib.go +++ b/lua/lauxlib.go @@ -1,29 +1,50 @@ package lua -//#include -//#include -//#include -//#include -//#include "golua.h" +/* +#cgo CFLAGS: -I ${SRCDIR} -I ${SRCDIR}/lua + +#include "golua.h" + +*/ import "C" -import "unsafe" -type LuaError struct { - code int - message string - stackTrace []LuaStackEntry +import ( + "os" + "unsafe" +) + +func (L *State) Lock() { + L.r.Lock() } -func (err *LuaError) Error() string { - return err.message +func (L *State) Unlock() { + L.r.Unlock() } -func (err *LuaError) Code() int { - return err.code +func abs(v int) int { + if v < 0 { + return v * (-1) + } + return v } -func (err *LuaError) StackTrace() []LuaStackEntry { - return err.stackTrace +// lua_xmove +func XMove(from *State, to *State, n int) { + defer from.r.Unlock() + defer to.r.Unlock() + from.r.Lock() + to.r.Lock() + C.lua_xmove(from.s, to.s, C.int(n)) +} + +func (L *State) CheckStackArg(narg int) { + if int(C.lua_gettop(L.s)) < abs(narg) { + format := "stack dosen't contains element" + CFormat := C.CString(format) + defer C.free(unsafe.Pointer(CFormat)) + C.lua_pushlstring(L.s, CFormat, C.size_t(len(format))) + C.lua_error(L.s) + } } // luaL_argcheck @@ -32,6 +53,8 @@ func (L *State) Argcheck(cond bool, narg int, extramsg string) { if !cond { Cextramsg := C.CString(extramsg) defer C.free(unsafe.Pointer(Cextramsg)) + defer L.r.Unlock() + L.r.Lock() C.luaL_argerror(L.s, C.int(narg), Cextramsg) } } @@ -40,6 +63,8 @@ func (L *State) Argcheck(cond bool, narg int, extramsg string) { func (L *State) ArgError(narg int, extramsg string) int { Cextramsg := C.CString(extramsg) defer C.free(unsafe.Pointer(Cextramsg)) + defer L.r.Unlock() + L.r.Lock() return int(C.luaL_argerror(L.s, C.int(narg), Cextramsg)) } @@ -47,27 +72,41 @@ func (L *State) ArgError(narg int, extramsg string) int { func (L *State) CallMeta(obj int, e string) int { Ce := C.CString(e) defer C.free(unsafe.Pointer(Ce)) + defer L.r.Unlock() + L.r.Lock() return int(C.luaL_callmeta(L.s, C.int(obj), Ce)) } // luaL_checkany func (L *State) CheckAny(narg int) { + defer L.r.Unlock() + L.r.Lock() + L.CheckStackArg(narg) C.luaL_checkany(L.s, C.int(narg)) } // luaL_checkinteger func (L *State) CheckInteger(narg int) int { + defer L.r.Unlock() + L.r.Lock() + L.CheckStackArg(narg) return int(C.luaL_checkinteger(L.s, C.int(narg))) } // luaL_checknumber func (L *State) CheckNumber(narg int) float64 { + defer L.r.Unlock() + L.r.Lock() + L.CheckStackArg(narg) return float64(C.luaL_checknumber(L.s, C.int(narg))) } // luaL_checkstring func (L *State) CheckString(narg int) string { var length C.size_t + defer L.r.Unlock() + L.r.Lock() + L.CheckStackArg(narg) return C.GoString(C.luaL_checklstring(L.s, C.int(narg), &length)) } @@ -81,6 +120,8 @@ func (L *State) CheckOption(narg int, def string, lst []string) int { // luaL_checktype func (L *State) CheckType(narg int, t LuaValType) { + defer L.r.Unlock() + L.r.Lock() C.luaL_checktype(L.s, C.int(narg), C.int(t)) } @@ -88,13 +129,15 @@ func (L *State) CheckType(narg int, t LuaValType) { func (L *State) CheckUdata(narg int, tname string) unsafe.Pointer { Ctname := C.CString(tname) defer C.free(unsafe.Pointer(Ctname)) + defer L.r.Unlock() + L.r.Lock() return unsafe.Pointer(C.luaL_checkudata(L.s, C.int(narg), Ctname)) } // Executes file, returns nil for no errors or the lua error string on failure func (L *State) DoFile(filename string) error { if r := L.LoadFile(filename); r != 0 { - return &LuaError{r, L.ToString(-1), L.StackTrace()} + return (&LuaError{}).New(L, r, L.ToString(-1)) } return L.Call(0, LUA_MULTRET) } @@ -102,7 +145,7 @@ func (L *State) DoFile(filename string) error { // Executes the string, returns nil for no errors or the lua error string on failure func (L *State) DoString(str string) error { if r := L.LoadString(str); r != 0 { - return &LuaError{r, L.ToString(-1), L.StackTrace()} + return (&LuaError{}).New(L, r, L.ToString(-1)) } return L.Call(0, LUA_MULTRET) } @@ -118,6 +161,8 @@ func (L *State) MustDoString(str string) { func (L *State) GetMetaField(obj int, e string) bool { Ce := C.CString(e) defer C.free(unsafe.Pointer(Ce)) + defer L.r.Unlock() + L.r.Lock() return C.luaL_getmetafield(L.s, C.int(obj), Ce) != 0 } @@ -125,6 +170,8 @@ func (L *State) GetMetaField(obj int, e string) bool { func (L *State) LGetMetaTable(tname string) { Ctname := C.CString(tname) defer C.free(unsafe.Pointer(Ctname)) + defer L.r.Unlock() + L.r.Lock() C.lua_getfield(L.s, LUA_REGISTRYINDEX, Ctname) } @@ -138,7 +185,8 @@ func (L *State) GSub(s string, p string, r string) string { C.free(unsafe.Pointer(Cp)) C.free(unsafe.Pointer(Cr)) }() - + defer L.r.Unlock() + L.r.Lock() return C.GoString(C.luaL_gsub(L.s, Cs, Cp, Cr)) } @@ -146,13 +194,17 @@ func (L *State) GSub(s string, p string, r string) string { func (L *State) LoadFile(filename string) int { Cfilename := C.CString(filename) defer C.free(unsafe.Pointer(Cfilename)) - return int(lualLoadFile(L.s, Cfilename)) + defer L.r.Unlock() + L.r.Lock() + return int(C.luaL_loadfile(L.s, Cfilename)) } // luaL_loadstring func (L *State) LoadString(s string) int { Cs := C.CString(s) defer C.free(unsafe.Pointer(Cs)) + defer L.r.Unlock() + L.r.Lock() return int(C.luaL_loadstring(L.s, Cs)) } @@ -175,36 +227,68 @@ func (L *State) Load(bs []byte, name string) int { return 0 } +// lua_newthread +func (L *State) NewThread() *State { + defer L.r.Unlock() + L.r.Lock() + s := C.lua_newthread(L.s) + return L.ToThreadHelper(s) +} + +// Creates a new user data object of specified size and returns it +func (L *State) NewUserdata(size uintptr) unsafe.Pointer { + defer L.r.Unlock() + L.r.Lock() + return unsafe.Pointer(C.lua_newuserdata(L.s, C.size_t(size))) +} + +// lua_newtable +func (L *State) NewTable() { + defer L.r.Unlock() + L.r.Lock() + C.lua_createtable(L.s, 0, 0) +} + // luaL_newmetatable func (L *State) NewMetaTable(tname string) bool { Ctname := C.CString(tname) defer C.free(unsafe.Pointer(Ctname)) + defer L.r.Unlock() + L.r.Lock() return C.luaL_newmetatable(L.s, Ctname) != 0 } -// luaL_newstate -func NewState() *State { - ls := (C.luaL_newstate()) - if ls == nil { - return nil - } - L := newState(ls) - return L -} - // luaL_openlibs func (L *State) OpenLibs() { + defer L.r.Unlock() + L.r.Lock() + // stop collector during initialization + C.lua_gc(L.s, LUA_GCSTOP, 0) C.luaL_openlibs(L.s) + C.lua_gc(L.s, LUA_GCRESTART, -1) C.clua_hide_pcall(L.s) + // load bundle loaders + C.bundle_add_loaders(L.s) + // load bundle main routine and initialize args + localArgc := C.int(len(os.Args)) + localArgv := make([]*C.char, len(os.Args)) + for i, arg := range os.Args { + localArgv[i] = C.CString(arg) + } + C.bundle_main(L.s, localArgc, &localArgv[0]) } // luaL_optinteger func (L *State) OptInteger(narg int, d int) int { + defer L.r.Unlock() + L.r.Lock() return int(C.luaL_optinteger(L.s, C.int(narg), C.lua_Integer(d))) } // luaL_optnumber func (L *State) OptNumber(narg int, d float64) float64 { + defer L.r.Unlock() + L.r.Lock() return float64(C.luaL_optnumber(L.s, C.int(narg), C.lua_Number(d))) } @@ -213,25 +297,267 @@ func (L *State) OptString(narg int, d string) string { var length C.size_t Cd := C.CString(d) defer C.free(unsafe.Pointer(Cd)) + defer L.r.Unlock() + L.r.Lock() return C.GoString(C.luaL_optlstring(L.s, C.int(narg), Cd, &length)) } // luaL_ref func (L *State) Ref(t int) int { + defer L.r.Unlock() + L.r.Lock() return int(C.luaL_ref(L.s, C.int(t))) } // luaL_typename func (L *State) LTypename(index int) string { + defer L.r.Unlock() + L.r.Lock() return C.GoString(C.lua_typename(L.s, C.lua_type(L.s, C.int(index)))) } // luaL_unref func (L *State) Unref(t int, ref int) { + defer L.r.Unlock() + L.r.Lock() C.luaL_unref(L.s, C.int(t), C.int(ref)) } // luaL_where func (L *State) Where(lvl int) { + defer L.r.Unlock() + L.r.Lock() C.luaL_where(L.s, C.int(lvl)) } + +// Sets a metamethod to execute a go function +// +// The code: +// +// L.LGetMetaTable(tableName) +// L.SetMetaMethod(methodName, function) +// +// is the logical equivalent of: +// +// L.LGetMetaTable(tableName) +// L.PushGoFunction(function) +// L.SetField(-2, methodName) +// +// except this wouldn't work because pushing a go function results in user data not a cfunction +func (L *State) SetMetaMethod(methodName string, f LuaGoFunction) { + L.PushGoFunction(f) // leaves Go function userdata on stack + defer L.r.Unlock() + L.r.Lock() + C.clua_pushcallback(L.s) // wraps the userdata object with a closure making it into a function + L.SetField(-2, methodName) +} + +// lua_getfenv +func (L *State) GetfEnv(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_getfenv(L.s, C.int(index)) +} + +// lua_setfenv +func (L *State) SetfEnv(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_setfenv(L.s, C.int(index)) +} + +// lua_getfield +func (L *State) GetField(index int, k string) { + Ck := C.CString(k) + defer C.free(unsafe.Pointer(Ck)) + defer L.r.Unlock() + L.r.Lock() + C.lua_getfield(L.s, C.int(index), Ck) +} + +// lua_setfield +func (L *State) SetField(index int, k string) { + Ck := C.CString(k) + defer C.free(unsafe.Pointer(Ck)) + defer L.r.Unlock() + L.r.Lock() + C.lua_setfield(L.s, C.int(index), Ck) +} + +// lua_gettable +func (L *State) GetTable(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_gettable(L.s, C.int(index)) +} + +// lua_settable +func (L *State) SetTable(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_settable(L.s, C.int(index)) +} + +// lua_getmetatable +func (L *State) GetMetaTable(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.lua_getmetatable(L.s, C.int(index)) != 0 +} + +// lua_setmetatable +func (L *State) SetMetaTable(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_setmetatable(L.s, C.int(index)) +} + +// lua_rawequal +func (L *State) RawEqual(index1 int, index2 int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.lua_rawequal(L.s, C.int(index1), C.int(index2)) != 0 +} + +// lua_rawget +func (L *State) RawGet(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_rawget(L.s, C.int(index)) +} + +// lua_rawset +func (L *State) RawSet(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_rawset(L.s, C.int(index)) +} + +// lua_concat +func (L *State) Concat(n int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_concat(L.s, C.int(n)) +} + +// lua_equal +func (L *State) Equal(index1, index2 int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.lua_equal(L.s, C.int(index1), C.int(index2)) == 1 +} + +// lua_lessthan +func (L *State) LessThan(index1, index2 int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.lua_lessthan(L.s, C.int(index1), C.int(index2)) == 1 +} + +// lua_objlen +// +// Returns the "length" of the value at the +// given acceptable index: for strings, this +// is the string length; for tables, this +// is the result of the length operator ('#'); +// for userdata, this is the size of the block +// of memory allocated for the userdata; +// for other values, it is 0. +// jea note: Despite the misleading description +// above, in 5.1 or LuaJit, ObjLen does not call +// the metamethod __len(). In 5.2 it was split +// into len and rawlen, with len calling the __len +// metamethod. +// +func (L *State) ObjLen(index int) uint { + defer L.r.Unlock() + L.r.Lock() + return uint(C.lua_objlen(L.s, C.int(index))) +} + +// lua_yield +func (L *State) Yield(nresults int) int { + defer L.r.Unlock() + L.r.Lock() + return int(C.lua_yield(L.s, C.int(nresults))) +} + +// lua_resume +func (L *State) Resume(narg int) int { + defer L.r.Unlock() + L.r.Lock() + return int(C.lua_resume(L.s, C.int(narg))) +} + +// lua_next +func (L *State) Next(index int) int { + defer L.r.Unlock() + L.r.Lock() + return int(C.lua_next(L.s, C.int(index))) +} + +// lua_status +func (L *State) Status() int { + defer L.r.Unlock() + L.r.Lock() + return int(C.lua_status(L.s)) +} + +// lua_setallocf +func (L *State) SetAllocf(f Alloc) { + defer L.r.Unlock() + L.r.Lock() + L.allocfn = &f + C.clua_setallocf(L.s, unsafe.Pointer(L.allocfn)) +} + +// Restricted library opens + +// Calls luaopen_base +func (L *State) OpenBase() { + defer L.r.Unlock() + L.r.Lock() + C.clua_openbase(L.s) +} + +// Calls luaopen_io +func (L *State) OpenIO() { + defer L.r.Unlock() + L.r.Lock() + C.clua_openio(L.s) +} + +// Calls luaopen_math +func (L *State) OpenMath() { + defer L.r.Unlock() + L.r.Lock() + C.clua_openmath(L.s) +} + +// Calls luaopen_package +func (L *State) OpenPackage() { + defer L.r.Unlock() + L.r.Lock() + C.clua_openpackage(L.s) +} + +// Calls luaopen_string +func (L *State) OpenString() { + defer L.r.Unlock() + L.r.Lock() + C.clua_openstring(L.s) +} + +// Calls luaopen_table +func (L *State) OpenTable() { + defer L.r.Unlock() + L.r.Lock() + C.clua_opentable(L.s) +} + +// Calls luaopen_os +func (L *State) OpenOS() { + defer L.r.Unlock() + L.r.Lock() + C.clua_openos(L.s) +} diff --git a/lua/lerr.go b/lua/lerr.go new file mode 100644 index 0000000..038de61 --- /dev/null +++ b/lua/lerr.go @@ -0,0 +1,302 @@ +package lua + +/* +#cgo CFLAGS: -I ${SRCDIR} -I ${SRCDIR}/lua + +#include "golua.h" + +*/ +import "C" + +import ( + "bytes" + "encoding/json" + "fmt" + "runtime" + "strconv" + "strings" + "unsafe" +) + +const goRuntimeMaxDeeps int = 50 + +type LuaStackEntry struct { + Name string `json:"name"` + Source string `json:"source"` + ShortSource string `json:"short_source"` + CurrentLine int `json:"line"` +} + +type GoStackEntry struct { + Name string `json:"func"` + Source string `json:"file"` + CurrentLine int `json:"line"` +} + +type LuaError struct { + Code int `json:"code"` + Msg string `json:"message"` + LuaS []string `json:"lua_stack"` + LuaST []LuaStackEntry `json:"lua_stacktrace"` + GoST []GoStackEntry `json:"go_stacktrace"` +} + +func (le *LuaError) Error() string { + buffer := bytes.Buffer{} + buffer.WriteString(fmt.Sprintf("lua error code: %d; %s\n", le.Code, le.Msg)) + buffer.WriteString("Lua current stack dump:\n") + for _, entry := range le.LuaS { + buffer.WriteString(entry) + } + buffer.WriteString("Lua error stack trace:\n") + for _, entry := range le.LuaST { + buffer.WriteString(" at ") + buffer.WriteString(entry.Name) + buffer.WriteString("( ") + buffer.WriteString(entry.Source) + buffer.WriteString(":") + buffer.WriteString(strconv.Itoa(entry.CurrentLine)) + buffer.WriteString(" )\n") + } + buffer.WriteString("Go error stack trace:\n") + for _, entry := range le.GoST { + buffer.WriteString(" at ") + buffer.WriteString(entry.Name) + buffer.WriteString("( ") + buffer.WriteString(entry.Source) + buffer.WriteString(":") + buffer.WriteString(strconv.Itoa(entry.CurrentLine)) + buffer.WriteString(" )\n") + } + return buffer.String() +} + +func (le *LuaError) Parse(data string) error { + err := json.Unmarshal([]byte(data), le) + if err != nil { + return err + } + return nil +} + +func (le *LuaError) String() string { + data, err := json.Marshal(le) + if err != nil { + return "{}" + } + return string(data) +} + +func (le *LuaError) New(state *State, code int, msg string) *LuaError { + if le.Parse(msg) == nil { + return le + } + le = &LuaError{ + Code: code, + Msg: msg, + LuaS: state.LuaStack(), + LuaST: state.LuaStackTrace(), + GoST: state.GoStackTrace(), + } + return le +} + +// Sets the lua hook (lua_sethook). +// This and SetExecutionLimit are mutual exclusive +func (L *State) SetHook(f HookFunction, instrNumber int) { + defer L.r.Unlock() + L.r.Lock() + L.hookFn = f + C.clua_sethook(L.s, C.int(instrNumber)) +} + +// Sets the maximum number of operations to execute at instrNumber, after this the execution ends +// This and SetHook are mutual exclusive +func (L *State) SetExecutionLimit(instrNumber int) { + defer L.r.Unlock() + L.r.Lock() + L.SetHook(func(l *State) { + l.RaiseError(ExecutionQuantumExceeded) + }, instrNumber) +} + +// lua_error +func (L *State) RaiseError(msg string) { + L.PushString((&LuaError{}).New(L, 0, msg).String()) + C.lua_error(L.s) +} + +func (L *State) NewError(msg string) *LuaError { + return (&LuaError{}).New(L, 0, msg) +} + +// Returns the current lua stack trace +func (L *State) LuaStack() []string { + var ( + stack []string + top int + ) + + top = L.GetTop() + L.PushThread() + L.ToThread(-1) + L.SetTop(top) + for i := top; i >= 1; i-- { + stack = append(stack, L.LuaStackPosToString(i)) + } + return stack +} + +// Returns the current lua stack trace +func (L *State) LuaStackTrace() []LuaStackEntry { + r := []LuaStackEntry{} + var d C.lua_Debug + Sln := C.CString("Sln") + defer C.free(unsafe.Pointer(Sln)) + defer L.r.Unlock() + L.r.Lock() + + for depth := 0; C.lua_getstack(L.s, C.int(depth), &d) > 0; depth++ { + C.lua_getinfo(L.s, Sln, &d) + ssb := make([]byte, C.LUA_IDSIZE) + for i := 0; i < C.LUA_IDSIZE; i++ { + ssb[i] = byte(d.short_src[i]) + if ssb[i] == 0 { + ssb = ssb[:i] + break + } + } + ss := string(ssb) + + r = append(r, LuaStackEntry{C.GoString(d.name), C.GoString(d.source), ss, int(d.currentline)}) + } + + return r +} + +// Returns the current go runtime stack trace +func (L *State) GoStackTrace() []GoStackEntry { + pc := make([]uintptr, goRuntimeMaxDeeps) + result := make([]GoStackEntry, 0, goRuntimeMaxDeeps) + runtime.Callers(2, pc) + frames := runtime.CallersFrames(pc) + skipMod := true + for frame, ok := frames.Next(); ok; frame, ok = frames.Next() { + if skipMod { + if strings.HasSuffix(frame.Function, "GoStackTrace") { + continue + } + if strings.HasSuffix(frame.Function, "(*LuaError).New") { + continue + } + skipMod = false + } + result = append(result, GoStackEntry{ + Name: frame.Function, + Source: frame.File, + CurrentLine: frame.Line, + }) + } + return result +} + +func (L *State) DumpLuaStack() { + fmt.Printf("\n%s\n", L.DumpLuaStackAsString()) +} + +func (L *State) DumpLuaStackAsString() (s string) { + top := L.GetTop() + isMain := L.PushThread() + thr := L.ToThread(-1) + L.SetTop(top) + s += "==begin DumpLuaStack" + s += fmt.Sprintf(" (of coro %p/lua.State=%p; isMain=%v): top = %v\n", thr, thr.s, isMain, top) + for i := top; i >= 1; i-- { + + t := L.Type(i) + s += fmt.Sprintf("DumpLuaStack: i=%v, t= %v\n", i, t) + s += L.LuaStackPosToString(i) + } + s += "==end of DumpLuaStack\n" + return +} + +func (L *State) LuaStackPosToString(i int) string { + t := L.Type(i) + + switch t { + case LUA_TNONE: // -1 + return fmt.Sprintf(" LUA_TNONE; i=%v was invalid index\n", i) + case LUA_TNIL: + return fmt.Sprintf(" LUA_TNIL: %v\n", nil) + case LUA_TSTRING: + return fmt.Sprintf(" String : \t%v\n", L.ToString(i)) + case LUA_TBOOLEAN: + return fmt.Sprintf(" Bool : \t\t%v\n", L.ToBoolean(i)) + case LUA_TNUMBER: + return fmt.Sprintf(" Number : \t%v\n", L.ToNumber(i)) + case LUA_TTABLE: + return fmt.Sprintf(" Table : \n%s\n", L.dumpTableString(i)) + + case 10: // LUA_TCDATA aka cdata + ctype := L.LuaJITctypeID(i) + switch ctype { + case 5: // int8 + case 6: // uint8 + case 7: // int16 + case 8: // uint16 + case 9: // int32 + case 10: // uint32 + case 11: // int64 + val := L.CdataToInt64(i) + return fmt.Sprintf(" int64: '%v'\n", val) + case 12: // uint64 + val := L.CdataToUint64(i) + return fmt.Sprintf(" uint64: '%v'\n", val) + case 13: // float32 + case 14: // float64 + + case 0: // means it wasn't a ctype + } + + case LUA_TUSERDATA: + return fmt.Sprintf(" Type(code %v/ LUA_TUSERDATA) : 0x%x with pointer %p\n", t, L.ToPointer(i), L.ToUserdata(i)) + case LUA_TFUNCTION: + return fmt.Sprintf(" Type(code %v/ LUA_TFUNCTION) : 0x%x\n", t, L.ToPointer(i)) + case LUA_TTHREAD: + return fmt.Sprintf(" Type(code %v/ LUA_TTHREAD) : 0x%x\n", t, L.ToPointer(i)) + case LUA_TLIGHTUSERDATA: + return fmt.Sprintf(" Type(code %v/ LUA_TLIGHTUSERDATA) : 0x%x with pointer %p\n", t, L.ToPointer(i), L.ToUserdata(i)) + default: + } + return fmt.Sprintf(" Type(code %v) : 0x%x, no auto-print available.\n", t, L.ToPointer(i)) +} + +func (L *State) dumpTableString(index int) (s string) { + // Push another reference to the table on top of the stack (so we know + // where it is, and this function can work for negative, positive and + // pseudo indices + L.PushValue(index) + // stack now contains: -1 => table + L.PushNil() + // stack now contains: -1 => nil; -2 => table + for L.Next(-2) != 0 { + + // stack now contains: -1 => value; -2 => key; -3 => table + // copy the key so that lua_tostring does not modify the original + L.PushValue(-2) + // stack now contains: -1 => key; -2 => value; -3 => key; -4 => table + key := L.ToString(-1) + value := L.ToString(-2) + s += fmt.Sprintf("'%s' => '%s'\n", key, value) + // pop value + copy of key, leaving original key + L.Pop(2) + // stack now contains: -1 => key; -2 => table + } + // stack now contains: -1 => table (when lua_next returns 0 it pops the key + // but does not push anything.) + // Pop table + L.Pop(1) + // Stack is now the same as it was on entry to this function + return +} diff --git a/lua/lib/linux32/libbundle.a b/lua/lib/linux32/libbundle.a new file mode 100644 index 0000000..e744163 Binary files /dev/null and b/lua/lib/linux32/libbundle.a differ diff --git a/lua/lib/linux32/libluajit.a b/lua/lib/linux32/libluajit.a new file mode 100644 index 0000000..a37bb87 Binary files /dev/null and b/lua/lib/linux32/libluajit.a differ diff --git a/lua/lib/linux64/libbundle.a b/lua/lib/linux64/libbundle.a new file mode 100755 index 0000000..61ca827 Binary files /dev/null and b/lua/lib/linux64/libbundle.a differ diff --git a/lua/lib/linux64/libluajit.a b/lua/lib/linux64/libluajit.a new file mode 100644 index 0000000..2a2ae6c Binary files /dev/null and b/lua/lib/linux64/libluajit.a differ diff --git a/lua/lib/mingw32/libbundle.a b/lua/lib/mingw32/libbundle.a new file mode 100644 index 0000000..aeab861 Binary files /dev/null and b/lua/lib/mingw32/libbundle.a differ diff --git a/lua/lib/mingw32/libluajit.a b/lua/lib/mingw32/libluajit.a new file mode 100644 index 0000000..ea89496 Binary files /dev/null and b/lua/lib/mingw32/libluajit.a differ diff --git a/lua/lib/mingw64/libbundle.a b/lua/lib/mingw64/libbundle.a new file mode 100644 index 0000000..fcaee65 Binary files /dev/null and b/lua/lib/mingw64/libbundle.a differ diff --git a/lua/lib/mingw64/libluajit.a b/lua/lib/mingw64/libluajit.a new file mode 100644 index 0000000..7c95aa3 Binary files /dev/null and b/lua/lib/mingw64/libluajit.a differ diff --git a/lua/lib/osx32/libbundle.a b/lua/lib/osx32/libbundle.a new file mode 100644 index 0000000..a0b7c23 Binary files /dev/null and b/lua/lib/osx32/libbundle.a differ diff --git a/lua/lib/osx32/libluajit.a b/lua/lib/osx32/libluajit.a new file mode 100644 index 0000000..4403022 Binary files /dev/null and b/lua/lib/osx32/libluajit.a differ diff --git a/lua/lib/osx64/libbundle.a b/lua/lib/osx64/libbundle.a new file mode 100644 index 0000000..6d8128e Binary files /dev/null and b/lua/lib/osx64/libbundle.a differ diff --git a/lua/lib/osx64/libluajit.a b/lua/lib/osx64/libluajit.a new file mode 100644 index 0000000..aa9c5bc Binary files /dev/null and b/lua/lib/osx64/libluajit.a differ diff --git a/lua/lstack.go b/lua/lstack.go new file mode 100644 index 0000000..b81c467 --- /dev/null +++ b/lua/lstack.go @@ -0,0 +1,215 @@ +package lua + +/* +#cgo CFLAGS: -I ${SRCDIR} -I ${SRCDIR}/lua + +#include "golua.h" + +*/ +import "C" + +import "unsafe" + +// lua_checkstack +func (L *State) CheckStack(extra int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.lua_checkstack(L.s, C.int(extra)) != 0 +} + +// lua_pop +func (L *State) Pop(n int) { + //Why is this implemented this way? I don't get it... maybe it + // is just inlining manually the actual implementation. + //C.lua_pop(L.s, C.int(n)) + defer L.r.Unlock() + L.r.Lock() + C.lua_settop(L.s, C.int(-n-1)) +} + +// lua_gettop +func (L *State) GetTop() int { + defer L.r.Unlock() + L.r.Lock() + return int(C.lua_gettop(L.s)) +} + +// lua_settop +func (L *State) SetTop(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_settop(L.s, C.int(index)) +} + +// Pushes on the stack the value of a global variable (lua_getglobal) +func (L *State) GetGlobal(name string) { + defer L.r.Unlock() + L.r.Lock() + L.GetField(LUA_GLOBALSINDEX, name) +} + +// lua_setglobal +func (L *State) SetGlobal(name string) { + Cname := C.CString(name) + defer C.free(unsafe.Pointer(Cname)) + defer L.r.Unlock() + L.r.Lock() + C.lua_setfield(L.s, C.int(LUA_GLOBALSINDEX), Cname) +} + +// lua_insert +func (L *State) Insert(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_insert(L.s, C.int(index)) +} + +// lua_remove +func (L *State) Remove(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_remove(L.s, C.int(index)) +} + +// lua_replace +func (L *State) Replace(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_replace(L.s, C.int(index)) +} + +// lua_rawgeti +func (L *State) RawGeti(index int, n int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_rawgeti(L.s, C.int(index), C.int(n)) +} + +// lua_rawseti +func (L *State) RawSeti(index int, n int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_rawseti(L.s, C.int(index), C.int(n)) +} + +// lua_createtable +func (L *State) CreateTable(narr int, nrec int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_createtable(L.s, C.int(narr), C.int(nrec)) +} + +// Like lua_pushcfunction pushes onto the stack a go function as user data +func (L *State) PushGoFunction(f LuaGoFunction) { + defer L.r.Unlock() + L.r.Lock() + fid := L.register(f) + C.clua_pushgofunction(L.s, C.uint(fid)) +} + +// PushGoClosure pushes a lua.LuaGoFunction to the stack wrapped in a Closure. +// this permits the go function to reflect lua type 'function' when checking with type() +// this implements behaviour akin to lua_pushcfunction() in lua C API. +func (L *State) PushGoClosure(f LuaGoFunction) { + L.PushGoFunction(f) // leaves Go function userdata on stack + defer L.r.Unlock() + L.r.Lock() + C.clua_pushcallback(L.s) // wraps the userdata object with a closure making it into a function +} + +func (L *State) PushInt64(n int64) { + defer L.r.Unlock() + L.r.Lock() + C.clua_luajit_push_cdata_int64(L.s, C.int64_t(n)) +} + +func (L *State) PushUint64(u uint64) { + defer L.r.Unlock() + L.r.Lock() + C.clua_luajit_push_cdata_uint64(L.s, C.uint64_t(u)) +} + +// Pushes a Go struct onto the stack as user data. +// +// The user data will be rigged so that lua code can access +// and change the public members of simple types directly +func (L *State) PushGoStruct(iface interface{}) { + defer L.r.Unlock() + L.r.Lock() + iid := L.register(iface) + C.clua_pushgostruct(L.s, C.uint(iid)) +} + +// Push a pointer onto the stack as user data. +// +// This function doesn't save a reference to the interface, +// it is the responsibility of the caller of this function to insure +// that the interface outlasts the lifetime of the lua object that this function creates. +func (L *State) PushLightUserdata(ud *interface{}) { + defer L.r.Unlock() + L.r.Lock() + C.lua_pushlightuserdata(L.s, unsafe.Pointer(ud)) +} + +// lua_pushstring +func (L *State) PushString(str string) { + Cstr := C.CString(str) + defer C.free(unsafe.Pointer(Cstr)) + defer L.r.Unlock() + L.r.Lock() + C.lua_pushlstring(L.s, Cstr, C.size_t(len(str))) +} + +func (L *State) PushBytes(b []byte) { + defer L.r.Unlock() + L.r.Lock() + C.lua_pushlstring(L.s, (*C.char)(unsafe.Pointer(&b[0])), C.size_t(len(b))) +} + +// lua_pushinteger +func (L *State) PushInteger(n int64) { + defer L.r.Unlock() + L.r.Lock() + C.lua_pushinteger(L.s, C.lua_Integer(n)) +} + +// lua_pushnil +func (L *State) PushNil() { + defer L.r.Unlock() + L.r.Lock() + C.lua_pushnil(L.s) +} + +// lua_pushnumber +func (L *State) PushNumber(n float64) { + defer L.r.Unlock() + L.r.Lock() + C.lua_pushnumber(L.s, C.lua_Number(n)) // lua_Number is a cast +} + +// lua_pushboolean +func (L *State) PushBoolean(b bool) { + var bint int + if b { + bint = 1 + } else { + bint = 0 + } + defer L.r.Unlock() + L.r.Lock() + C.lua_pushboolean(L.s, C.int(bint)) +} + +// lua_pushthread +func (L *State) PushThread() (isMain bool) { + defer L.r.Unlock() + L.r.Lock() + return C.lua_pushthread(L.s) != 0 +} + +// lua_pushvalue +func (L *State) PushValue(index int) { + defer L.r.Unlock() + L.r.Lock() + C.lua_pushvalue(L.s, C.int(index)) +} diff --git a/lua/lstate.go b/lua/lstate.go new file mode 100644 index 0000000..159ea44 --- /dev/null +++ b/lua/lstate.go @@ -0,0 +1,207 @@ +package lua + +/* +#cgo CFLAGS: -I ${SRCDIR} -I ${SRCDIR}/lua + +#include "golua.h" + +*/ +import "C" +import ( + "unsafe" + + "github.com/vxcontrol/rmx" +) + +// luaL_newstate +func NewState() *State { + ls := (C.luaL_newstate()) + if ls == nil { + return nil + } + L := newState(ls) + return L +} + +// Creates a new lua interpreter state with the given allocation function +func NewStateAlloc(f Alloc) *State { + // jea: ../example/alloc.go panics... hmm. + ls := C.clua_newstate(unsafe.Pointer(&f)) + L := newState(ls) + L.allocfn = &f + return L +} + +// luaL_loadbuffer +func (L *State) LoadBuffer(data []byte, size int, name string) int { + Cname := C.CString(name) + Cdata := (*C.char)(unsafe.Pointer(&data[0])) + defer C.free(unsafe.Pointer(Cname)) + defer L.r.Unlock() + L.r.Lock() + return int(C.luaL_loadbuffer(L.s, Cdata, C.size_t(size), Cname)) +} + +// lua_call +func (L *State) Call(nargs, nresults int) error { + return L.callEx(nargs, nresults) +} + +// Like lua_call but panics on errors +func (L *State) MustCall(nargs, nresults int) { + if err := L.callEx(nargs, nresults); err != nil { + panic(err) + } +} + +func (L *State) GetState() *C.lua_State { + defer L.r.Unlock() + L.r.Lock() + return L.s +} + +// lua_gc +func (L *State) GC(what, data int) int { + defer L.r.Unlock() + L.r.Lock() + return int(C.lua_gc(L.s, C.int(what), C.int(data))) +} + +// Registers a Go function as a global variable +func (L *State) Register(name string, f LuaGoFunction) { + L.PushGoFunction(f) + L.SetGlobal(name) +} + +// lua_close +func (L *State) Close() { + defer L.r.Unlock() + L.r.Lock() + C.lua_close(L.s) + unregisterGoState(L) +} + +func newState(L *C.lua_State) *State { + newstate := &State{ + s: L, + r: &rmx.Mutex{}, + Shared: newSharedByAllCoroutines(), + IsMainCoro: true, + CmainCo: L, + AllCoro: make(map[int]*State), + } + newstate.MainCo = newstate + defer newstate.r.Unlock() + newstate.r.Lock() + + // only for main states, not additional coroutines: + registerGoState(newstate) // sets Index + newstate.Upos = int(C.clua_setgostate(L, C.size_t(newstate.Index))) + + // assert(Upos == 1) + if newstate.Upos != 1 { + panic("assert violated: we expected newstate.Upos for the main coro to always be at index 1: our code depends on that!") + } + newstate.MainCo.AllCoro[newstate.Upos] = newstate + C.clua_initstate(L) + return newstate +} + +func (L *State) getFreeIndex() (index uint, ok bool) { + freelen := len(L.Shared.freeIndices) + //if there exist entries in the freelist + if freelen > 0 { + i := L.Shared.freeIndices[freelen-1] //get index + L.Shared.freeIndices = L.Shared.freeIndices[0 : freelen-1] //'pop' index from list + return i, true + } + return 0, false +} + +//returns the registered function id +func (L *State) register(f interface{}) uint { + index, ok := L.getFreeIndex() + if ok { + // reuse + L.Shared.registry[index] = f + return index + } + // add a new index + L.Shared.registry = append(L.Shared.registry, f) + index = uint(len(L.Shared.registry)) - 1 + return index +} + +func (L *State) unregister(fid uint) { + if (fid < uint(len(L.Shared.registry))) && (L.Shared.registry[fid] != nil) { + L.Shared.registry[fid] = nil + L.Shared.freeIndices = append(L.Shared.freeIndices, fid) + } +} + +// Sets the AtPanic function, returns the old one +// +// BUG(everyone_involved): passing nil causes serious problems +func (L *State) AtPanic(panicf LuaGoFunction) (oldpanicf LuaGoFunction) { + defer L.r.Unlock() + L.r.Lock() + fid := uint(0) + if panicf != nil { + fid = L.register(panicf) + } + oldres := C.clua_atpanic(L.s, C.uint(fid)) + switch oldres.t { + case 1: + i := (*C.uint)(oldres.v) + f := L.Shared.registry[uint(*i)].(LuaGoFunction) + //free registry entry + L.unregister(uint(*i)) + return f + case 2: + i := (C.lua_CFunction)(oldres.v) + return func(L1 *State) int { + defer L1.r.Unlock() + L1.r.Lock() + return int(C.clua_callluacfunc(L1.s, i)) + } + } + //generally we only get here if the panicf got set to something like nil + //potentially dangerous because we may silently fail + return nil +} + +func (L *State) pcall(nargs, nresults, errfunc int) int { + defer L.r.Unlock() + L.r.Lock() + return int(C.lua_pcall(L.s, C.int(nargs), C.int(nresults), C.int(errfunc))) +} + +func (L *State) callEx(nargs, nresults int) (err error) { + defer func() { + if errRec := recover(); errRec != nil { + if _, ok := errRec.(error); ok { + err = errRec.(error) + } + return + } + }() + + L.GetGlobal(C.GOLUA_DEFAULT_MSGHANDLER) + // We must record where we put the error handler in the stack otherwise it will be impossible to remove after the pcall when nresults == LUA_MULTRET + erridx := L.GetTop() - nargs - 1 + L.Insert(erridx) + r := L.pcall(nargs, nresults, erridx) + L.Remove(erridx) + if r != 0 { + le := &LuaError{} + if err := le.Parse(L.ToString(-1)); err != nil { + le = le.New(L, r, L.ToString(-1)) + L.Pop(-1) + L.PushString(le.Error()) + } else { + le.Code = r + } + return le + } + return nil +} diff --git a/lua/ltypes.go b/lua/ltypes.go new file mode 100644 index 0000000..a448ecd --- /dev/null +++ b/lua/ltypes.go @@ -0,0 +1,322 @@ +package lua + +/* +#cgo CFLAGS: -I ${SRCDIR} -I ${SRCDIR}/lua + +#include "golua.h" + +*/ +import "C" +import ( + "unsafe" +) + +// Returns true if lua_type == LUA_TBOOLEAN +func (L *State) IsBoolean(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TBOOLEAN +} + +// Returns true if the value at index is a LuaGoFunction +func (L *State) IsGoFunction(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.clua_isgofunction(L.s, C.int(index)) != 0 +} + +// Returns true if the value at index is user data pushed with PushGoStruct +func (L *State) IsGoStruct(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.clua_isgostruct(L.s, C.int(index)) != 0 +} + +// Returns true if the value at index is user data pushed with PushGoFunction +func (L *State) IsFunction(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TFUNCTION +} + +// Returns true if the value at index is light user data +func (L *State) IsLightUserdata(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TLIGHTUSERDATA +} + +// lua_isnil +func (L *State) IsNil(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TNIL +} + +// lua_isnone +func (L *State) IsNone(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TNONE +} + +// lua_isnoneornil +func (L *State) IsNoneOrNil(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return int(C.lua_type(L.s, C.int(index))) <= 0 +} + +// lua_isnumber +func (L *State) IsNumber(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.lua_isnumber(L.s, C.int(index)) == 1 +} + +// lua_isstring +func (L *State) IsString(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.lua_isstring(L.s, C.int(index)) == 1 +} + +// lua_istable +func (L *State) IsTable(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TTABLE +} + +// lua_isthread +func (L *State) IsThread(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TTHREAD +} + +// lua_isuserdata +func (L *State) IsUserdata(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.lua_isuserdata(L.s, C.int(index)) == 1 +} + +// lua_tointeger +func (L *State) ToInteger(index int) int { + defer L.r.Unlock() + L.r.Lock() + return int(C.lua_tointeger(L.s, C.int(index))) +} + +// lua_tointeger +func (L *State) ToInteger32(index int) int32 { + defer L.r.Unlock() + L.r.Lock() + return int32(C.lua_tointeger(L.s, C.int(index))) +} + +// lua_tointeger +func (L *State) ToInteger64(index int) int64 { + defer L.r.Unlock() + L.r.Lock() + return int64(C.lua_tointeger(L.s, C.int(index))) +} + +// lua_tointeger +func (L *State) ToUInteger(index int) uint { + defer L.r.Unlock() + L.r.Lock() + return uint(C.lua_tointeger(L.s, C.int(index))) +} + +// lua_tointeger +func (L *State) ToUInteger32(index int) uint32 { + defer L.r.Unlock() + L.r.Lock() + return uint32(C.lua_tointeger(L.s, C.int(index))) +} + +// lua_tointeger +func (L *State) ToUInteger64(index int) uint64 { + defer L.r.Unlock() + L.r.Lock() + return uint64(C.lua_tointeger(L.s, C.int(index))) +} + +// lua_tointeger +func (L *State) ToFloat32(index int) float32 { + defer L.r.Unlock() + L.r.Lock() + return float32(C.lua_tonumber(L.s, C.int(index))) +} + +// lua_tointeger +func (L *State) ToFloat64(index int) float64 { + defer L.r.Unlock() + L.r.Lock() + return float64(C.lua_tonumber(L.s, C.int(index))) +} + +// lua_tonumber +func (L *State) ToNumber(index int) float64 { + defer L.r.Unlock() + L.r.Lock() + return float64(C.lua_tonumber(L.s, C.int(index))) +} + +// lua_toboolean +func (L *State) ToBoolean(index int) bool { + defer L.r.Unlock() + L.r.Lock() + return C.lua_toboolean(L.s, C.int(index)) != 0 +} + +// Returns the value at index as a Go function (it must be something pushed with PushGoFunction) +func (L *State) ToGoFunction(index int) (f LuaGoFunction) { + if !L.IsGoFunction(index) { + return nil + } + defer L.r.Unlock() + L.r.Lock() + fid := C.clua_togofunction(L.s, C.int(index)) + if fid < 0 { + return nil + } + return L.Shared.registry[fid].(LuaGoFunction) +} + +// Returns the value at index as a Go Struct (it must be something pushed with PushGoStruct) +func (L *State) ToGoStruct(index int) (f interface{}) { + if !L.IsGoStruct(index) { + return nil + } + defer L.r.Unlock() + L.r.Lock() + fid := C.clua_togostruct(L.s, C.int(index)) + if fid < 0 { + return nil + } + return L.Shared.registry[fid] +} + +// lua_tostring +func (L *State) ToString(index int) string { + var size C.size_t + defer L.r.Unlock() + L.r.Lock() + r := C.lua_tolstring(L.s, C.int(index), &size) + return C.GoStringN(r, C.int(size)) +} + +func (L *State) ToBytes(index int) []byte { + var size C.size_t + defer L.r.Unlock() + L.r.Lock() + b := C.lua_tolstring(L.s, C.int(index), &size) + return C.GoBytes(unsafe.Pointer(b), C.int(size)) +} + +// lua_topointer +func (L *State) ToPointer(index int) uintptr { + defer L.r.Unlock() + L.r.Lock() + return uintptr(C.lua_topointer(L.s, C.int(index))) +} + +// lua_tothread +func (L *State) ToThread(index int) *State { + defer L.r.Unlock() + L.r.Lock() + ptr := (*C.lua_State)(unsafe.Pointer(C.lua_tothread(L.s, C.int(index)))) + if ptr == nil { + return nil + } + return L.ToThreadHelper(ptr) +} + +func (L *State) ToThreadHelper(ptr *C.lua_State) *State { + if ptr == nil { + return nil + } + defer L.r.Unlock() + L.r.Lock() + upos := int(C.clua_dedup_coro(ptr)) + already := L.MainCo.AllCoro[upos] + if already != nil { + return already + } + + newstate := &State{ + s: ptr, + r: L.r, + Shared: L.Shared, + MainCo: L.MainCo, + CmainCo: L.MainCo.s, + Index: -1, // not the main state/main thread. + Upos: upos, + } + // don't register non-main threads in gostates[]. + + // asserts that (Upos != 1) + if newstate.Upos == 1 { + panic("assert violated: we expected newstate.Upos to not be 1 for any non-main thread/coroutine stated! our code in c-golua.c depends on that") + + } + if newstate.Upos == -1 { + panic("assert violated: we expected newstate.Upos to not be -1 for any not known coroutine!") + + } + newstate.MainCo.AllCoro[newstate.Upos] = newstate + return newstate +} + +// lua_touserdata +func (L *State) ToUserdata(index int) unsafe.Pointer { + defer L.r.Unlock() + L.r.Lock() + return unsafe.Pointer(C.lua_touserdata(L.s, C.int(index))) +} + +// lua_cdata_to_int64 +func (L *State) CdataToInt64(index int) int64 { + defer L.r.Unlock() + L.r.Lock() + return int64(C.lua_cdata_to_int64(L.s, C.int(index))) +} + +// lua_cdata_to_int32 +func (L *State) CdataToInt32(index int) int32 { + defer L.r.Unlock() + L.r.Lock() + return int32(C.lua_cdata_to_int32(L.s, C.int(index))) +} + +// lua_cdata_to_uint64 +func (L *State) CdataToUint64(index int) uint64 { + defer L.r.Unlock() + L.r.Lock() + return uint64(C.lua_cdata_to_uint64(L.s, C.int(index))) +} + +// LuaJIT only: return ctype of the cdata at the top of the stack. +func (L *State) LuaJITctypeID(idx int) uint32 { + defer L.r.Unlock() + L.r.Lock() + res := C.clua_luajit_ctypeid(L.s, C.int(idx)) + return uint32(res) +} + +// lua_type +func (L *State) Type(index int) LuaValType { + defer L.r.Unlock() + L.r.Lock() + return LuaValType(C.lua_type(L.s, C.int(index))) +} + +// lua_typename +func (L *State) Typename(tp int) string { + defer L.r.Unlock() + L.r.Lock() + return C.GoString(C.lua_typename(L.s, C.int(tp))) +} diff --git a/lua/lua.go b/lua/lua.go index df6467a..ae246c3 100644 --- a/lua/lua.go +++ b/lua/lua.go @@ -6,631 +6,13 @@ package lua /* -#cgo !lua52,!lua53,!lua54 CFLAGS: -I ${SRCDIR}/lua51 -#cgo lua52 CFLAGS: -I ${SRCDIR}/lua52 -#cgo lua53 CFLAGS: -I ${SRCDIR}/lua53 -#cgo lua54 CFLAGS: -I ${SRCDIR}/lua54 -#cgo llua LDFLAGS: -llua - -#cgo luaa LDFLAGS: -llua -lm -ldl -#cgo luajit LDFLAGS: -lluajit-5.1 -#cgo lluadash5.1 LDFLAGS: -llua-5.1 - -#cgo linux,!lua52,!lua53,!lua54,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua5.1 -#cgo linux,lua52,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua5.2 -#cgo linux,lua53,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua5.3 -#cgo linux,lua54,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua5.4 -lm - -#cgo darwin,!lua52,!lua53,!lua54,!llua,!luaa,!luajit,!lluadash5.1 pkg-config: lua5.1 -#cgo darwin,lua52,!llua,!luaa,!luajit,!lluadash5.1 pkg-config: lua5.2 -#cgo darwin,lua53,!llua,!luaa,!luajit,!lluadash5.1 pkg-config: lua5.3 -#cgo darwin,lua54,!llua,!luaa,!luajit,!lluadash5.1 pkg-config: lua5.4 m - -#cgo freebsd,!lua52,!lua53,!lua54,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua-5.1 -#cgo freebsd,lua52,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua-5.2 -#cgo freebsd,lua53,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua-5.3 -#cgo freebsd,lua54,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua-5.4 -lm - -#cgo windows,!lua52,!lua53,!lua54,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -L${SRCDIR} -llua -lmingwex -lmingw32 -#cgo windows,lua52,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua52 -#cgo windows,lua53,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua53 -#cgo windows,lua54,!llua,!luaa,!luajit,!lluadash5.1 LDFLAGS: -llua54 - -#include -#include - -#include "golua.h" +#cgo CFLAGS: -I ${SRCDIR} -I ${SRCDIR}/lua +#cgo linux,386 LDFLAGS: -L ${SRCDIR}/lib/linux32 -lbundle -lluajit -lm -ldl +#cgo linux,amd64 LDFLAGS: -L ${SRCDIR}/lib/linux64 -lbundle -lluajit -lm -ldl +#cgo darwin,386 LDFLAGS: -L ${SRCDIR}/lib/osx32 -lbundle -lluajit +#cgo darwin,amd64 LDFLAGS: -L ${SRCDIR}/lib/osx64 -lbundle -lluajit +#cgo windows,386 LDFLAGS: -L ${SRCDIR}/lib/mingw32 -lbundle -lluajit -lmingwex -lmingw32 +#cgo windows,amd64 LDFLAGS: -L ${SRCDIR}/lib/mingw64 -lbundle -lluajit -lmingwex -lmingw32 */ import "C" -import ( - "fmt" - "unsafe" -) - -type LuaStackEntry struct { - Name string - Source string - ShortSource string - CurrentLine int -} - -func newState(L *C.lua_State) *State { - newstate := &State{L, 0, make([]interface{}, 0, 8), make([]uint, 0, 8), nil, nil} - registerGoState(newstate) - C.clua_setgostate(L, C.size_t(newstate.Index)) - C.clua_initstate(L) - return newstate -} - -func (L *State) addFreeIndex(i uint) { - freelen := len(L.freeIndices) - //reallocate if necessary - if freelen+1 > cap(L.freeIndices) { - newSlice := make([]uint, freelen, cap(L.freeIndices)*2) - copy(newSlice, L.freeIndices) - L.freeIndices = newSlice - } - //reslice - L.freeIndices = L.freeIndices[0 : freelen+1] - L.freeIndices[freelen] = i -} - -func (L *State) getFreeIndex() (index uint, ok bool) { - freelen := len(L.freeIndices) - //if there exist entries in the freelist - if freelen > 0 { - i := L.freeIndices[freelen-1] //get index - //fmt.Printf("Free indices before: %v\n", L.freeIndices) - L.freeIndices = L.freeIndices[0 : freelen-1] //'pop' index from list - //fmt.Printf("Free indices after: %v\n", L.freeIndices) - return i, true - } - return 0, false -} - -//returns the registered function id -func (L *State) register(f interface{}) uint { - //fmt.Printf("Registering %v\n") - index, ok := L.getFreeIndex() - //fmt.Printf("\tfreeindex: index = %v, ok = %v\n", index, ok) - //if not ok, then we need to add new index by extending the slice - if !ok { - index = uint(len(L.registry)) - //reallocate backing array if necessary - if index+1 > uint(cap(L.registry)) { - newcap := cap(L.registry) * 2 - if index+1 > uint(newcap) { - newcap = int(index + 1) - } - newSlice := make([]interface{}, index, newcap) - copy(newSlice, L.registry) - L.registry = newSlice - } - //reslice - L.registry = L.registry[0 : index+1] - } - //fmt.Printf("\tregistering %d %v\n", index, f) - L.registry[index] = f - return index -} - -func (L *State) unregister(fid uint) { - //fmt.Printf("Unregistering %d (len: %d, value: %v)\n", fid, len(L.registry), L.registry[fid]) - if (fid < uint(len(L.registry))) && (L.registry[fid] != nil) { - L.registry[fid] = nil - L.addFreeIndex(fid) - } -} - -// Like lua_pushcfunction pushes onto the stack a go function as user data -func (L *State) PushGoFunction(f LuaGoFunction) { - fid := L.register(f) - C.clua_pushgofunction(L.s, C.uint(fid)) -} - -// PushGoClosure pushes a lua.LuaGoFunction to the stack wrapped in a Closure. -// this permits the go function to reflect lua type 'function' when checking with type() -// this implements behaviour akin to lua_pushcfunction() in lua C API. -func (L *State) PushGoClosure(f LuaGoFunction) { - L.PushGoFunction(f) // leaves Go function userdata on stack - C.clua_pushcallback(L.s) // wraps the userdata object with a closure making it into a function -} - -// Sets a metamethod to execute a go function -// -// The code: -// -// L.LGetMetaTable(tableName) -// L.SetMetaMethod(methodName, function) -// -// is the logical equivalent of: -// -// L.LGetMetaTable(tableName) -// L.PushGoFunction(function) -// L.SetField(-2, methodName) -// -// except this wouldn't work because pushing a go function results in user data not a cfunction -func (L *State) SetMetaMethod(methodName string, f LuaGoFunction) { - L.PushGoFunction(f) // leaves Go function userdata on stack - C.clua_pushcallback(L.s) // wraps the userdata object with a closure making it into a function - L.SetField(-2, methodName) -} - -// Pushes a Go struct onto the stack as user data. -// -// The user data will be rigged so that lua code can access and change to public members of simple types directly -func (L *State) PushGoStruct(iface interface{}) { - iid := L.register(iface) - C.clua_pushgostruct(L.s, C.uint(iid)) -} - -// Push a pointer onto the stack as user data. -// -// This function doesn't save a reference to the interface, it is the responsibility of the caller of this function to insure that the interface outlasts the lifetime of the lua object that this function creates. -func (L *State) PushLightUserdata(ud *interface{}) { - //push - C.lua_pushlightuserdata(L.s, unsafe.Pointer(ud)) -} - -// Creates a new user data object of specified size and returns it -func (L *State) NewUserdata(size uintptr) unsafe.Pointer { - return unsafe.Pointer(C.lua_newuserdata(L.s, C.size_t(size))) -} - -// Sets the AtPanic function, returns the old one -// -// BUG(everyone_involved): passing nil causes serious problems -func (L *State) AtPanic(panicf LuaGoFunction) (oldpanicf LuaGoFunction) { - fid := uint(0) - if panicf != nil { - fid = L.register(panicf) - } - oldres := interface{}(C.clua_atpanic(L.s, C.uint(fid))) - switch i := oldres.(type) { - case C.uint: - f := L.registry[uint(i)].(LuaGoFunction) - //free registry entry - L.unregister(uint(i)) - return f - case C.lua_CFunction: - return func(L1 *State) int { - return int(C.clua_callluacfunc(L1.s, i)) - } - } - //generally we only get here if the panicf got set to something like nil - //potentially dangerous because we may silently fail - return nil -} - -func (L *State) callEx(nargs, nresults int, catch bool) (err error) { - if catch { - defer func() { - if err2 := recover(); err2 != nil { - if _, ok := err2.(error); ok { - err = err2.(error) - } - return - } - }() - } - - L.GetGlobal(C.GOLUA_DEFAULT_MSGHANDLER) - // We must record where we put the error handler in the stack otherwise it will be impossible to remove after the pcall when nresults == LUA_MULTRET - erridx := L.GetTop() - nargs - 1 - L.Insert(erridx) - r := L.pcall(nargs, nresults, erridx) - L.Remove(erridx) - if r != 0 { - err = &LuaError{r, L.ToString(-1), L.StackTrace()} - if !catch { - panic(err) - } - } - return -} - -// lua_call -func (L *State) Call(nargs, nresults int) (err error) { - return L.callEx(nargs, nresults, true) -} - -// Like lua_call but panics on errors -func (L *State) MustCall(nargs, nresults int) { - L.callEx(nargs, nresults, false) -} - -// lua_checkstack -func (L *State) CheckStack(extra int) bool { - return C.lua_checkstack(L.s, C.int(extra)) != 0 -} - -// lua_close -func (L *State) Close() { - C.lua_close(L.s) - unregisterGoState(L) -} - -// lua_concat -func (L *State) Concat(n int) { - C.lua_concat(L.s, C.int(n)) -} - -// lua_createtable -func (L *State) CreateTable(narr int, nrec int) { - C.lua_createtable(L.s, C.int(narr), C.int(nrec)) -} - -// lua_getfield -func (L *State) GetField(index int, k string) { - Ck := C.CString(k) - defer C.free(unsafe.Pointer(Ck)) - C.lua_getfield(L.s, C.int(index), Ck) -} - -// lua_getmetatable -func (L *State) GetMetaTable(index int) bool { - return C.lua_getmetatable(L.s, C.int(index)) != 0 -} - -// lua_gettable -func (L *State) GetTable(index int) { C.lua_gettable(L.s, C.int(index)) } - -// lua_gettop -func (L *State) GetTop() int { return int(C.lua_gettop(L.s)) } - -// Returns true if lua_type == LUA_TBOOLEAN -func (L *State) IsBoolean(index int) bool { - return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TBOOLEAN -} - -// Returns true if the value at index is a LuaGoFunction -func (L *State) IsGoFunction(index int) bool { - return C.clua_isgofunction(L.s, C.int(index)) != 0 -} - -// Returns true if the value at index is user data pushed with PushGoStruct -func (L *State) IsGoStruct(index int) bool { - return C.clua_isgostruct(L.s, C.int(index)) != 0 -} - -// Returns true if the value at index is user data pushed with PushGoFunction -func (L *State) IsFunction(index int) bool { - return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TFUNCTION -} - -// Returns true if the value at index is light user data -func (L *State) IsLightUserdata(index int) bool { - return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TLIGHTUSERDATA -} - -// lua_isnil -func (L *State) IsNil(index int) bool { return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TNIL } - -// lua_isnone -func (L *State) IsNone(index int) bool { return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TNONE } - -// lua_isnoneornil -func (L *State) IsNoneOrNil(index int) bool { return int(C.lua_type(L.s, C.int(index))) <= 0 } - -// lua_isnumber -func (L *State) IsNumber(index int) bool { return C.lua_isnumber(L.s, C.int(index)) == 1 } - -// lua_isstring -func (L *State) IsString(index int) bool { return C.lua_isstring(L.s, C.int(index)) == 1 } - -// lua_istable -func (L *State) IsTable(index int) bool { - return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TTABLE -} - -// lua_isthread -func (L *State) IsThread(index int) bool { - return LuaValType(C.lua_type(L.s, C.int(index))) == LUA_TTHREAD -} - -// lua_isuserdata -func (L *State) IsUserdata(index int) bool { return C.lua_isuserdata(L.s, C.int(index)) == 1 } - -// Creates a new lua interpreter state with the given allocation function -func NewStateAlloc(f Alloc) *State { - ls := C.clua_newstate(unsafe.Pointer(&f)) - L := newState(ls) - L.allocfn = &f - return L -} - -// lua_newtable -func (L *State) NewTable() { - C.lua_createtable(L.s, 0, 0) -} - -// lua_newthread -func (L *State) NewThread() *State { - //TODO: call newState with result from C.lua_newthread and return it - //TODO: should have same lists as parent - // but may complicate gc - s := C.lua_newthread(L.s) - return &State{s, 0, nil, nil, nil, nil} -} - -// lua_next -func (L *State) Next(index int) int { - return int(C.lua_next(L.s, C.int(index))) -} - -// lua_objlen -// lua_pop -func (L *State) Pop(n int) { - //Why is this implemented this way? I don't get it... - //C.lua_pop(L.s, C.int(n)); - C.lua_settop(L.s, C.int(-n-1)) -} - -// lua_pushboolean -func (L *State) PushBoolean(b bool) { - var bint int - if b { - bint = 1 - } else { - bint = 0 - } - C.lua_pushboolean(L.s, C.int(bint)) -} - -// lua_pushstring -func (L *State) PushString(str string) { - Cstr := C.CString(str) - defer C.free(unsafe.Pointer(Cstr)) - C.lua_pushlstring(L.s, Cstr, C.size_t(len(str))) -} - -func (L *State) PushBytes(b []byte) { - C.lua_pushlstring(L.s, (*C.char)(unsafe.Pointer(&b[0])), C.size_t(len(b))) -} - -// lua_pushinteger -func (L *State) PushInteger(n int64) { - C.lua_pushinteger(L.s, C.lua_Integer(n)) -} - -// lua_pushnil -func (L *State) PushNil() { - C.lua_pushnil(L.s) -} - -// lua_pushnumber -func (L *State) PushNumber(n float64) { - C.lua_pushnumber(L.s, C.lua_Number(n)) -} - -// lua_pushthread -func (L *State) PushThread() (isMain bool) { - return C.lua_pushthread(L.s) != 0 -} - -// lua_pushvalue -func (L *State) PushValue(index int) { - C.lua_pushvalue(L.s, C.int(index)) -} - -// lua_rawequal -func (L *State) RawEqual(index1 int, index2 int) bool { - return C.lua_rawequal(L.s, C.int(index1), C.int(index2)) != 0 -} - -// lua_rawget -func (L *State) RawGet(index int) { - C.lua_rawget(L.s, C.int(index)) -} - -// lua_rawset -func (L *State) RawSet(index int) { - C.lua_rawset(L.s, C.int(index)) -} - -// Registers a Go function as a global variable -func (L *State) Register(name string, f LuaGoFunction) { - L.PushGoFunction(f) - L.SetGlobal(name) -} - -// lua_setallocf -func (L *State) SetAllocf(f Alloc) { - L.allocfn = &f - C.clua_setallocf(L.s, unsafe.Pointer(L.allocfn)) -} - -// lua_setfield -func (L *State) SetField(index int, k string) { - Ck := C.CString(k) - defer C.free(unsafe.Pointer(Ck)) - C.lua_setfield(L.s, C.int(index), Ck) -} - -// lua_setmetatable -func (L *State) SetMetaTable(index int) { - C.lua_setmetatable(L.s, C.int(index)) -} - -// lua_settable -func (L *State) SetTable(index int) { - C.lua_settable(L.s, C.int(index)) -} - -// lua_settop -func (L *State) SetTop(index int) { - C.lua_settop(L.s, C.int(index)) -} - -// lua_status -func (L *State) Status() int { - return int(C.lua_status(L.s)) -} - -// lua_toboolean -func (L *State) ToBoolean(index int) bool { - return C.lua_toboolean(L.s, C.int(index)) != 0 -} - -// Returns the value at index as a Go function (it must be something pushed with PushGoFunction) -func (L *State) ToGoFunction(index int) (f LuaGoFunction) { - if !L.IsGoFunction(index) { - return nil - } - fid := C.clua_togofunction(L.s, C.int(index)) - if fid < 0 { - return nil - } - return L.registry[fid].(LuaGoFunction) -} - -// Returns the value at index as a Go Struct (it must be something pushed with PushGoStruct) -func (L *State) ToGoStruct(index int) (f interface{}) { - if !L.IsGoStruct(index) { - return nil - } - fid := C.clua_togostruct(L.s, C.int(index)) - if fid < 0 { - return nil - } - return L.registry[fid] -} - -// lua_tostring -func (L *State) ToString(index int) string { - var size C.size_t - r := C.lua_tolstring(L.s, C.int(index), &size) - return C.GoStringN(r, C.int(size)) -} - -func (L *State) ToBytes(index int) []byte { - var size C.size_t - b := C.lua_tolstring(L.s, C.int(index), &size) - return C.GoBytes(unsafe.Pointer(b), C.int(size)) -} - -// lua_topointer -func (L *State) ToPointer(index int) uintptr { - return uintptr(C.lua_topointer(L.s, C.int(index))) -} - -// lua_tothread -func (L *State) ToThread(index int) *State { - //TODO: find a way to link lua_State* to existing *State, return that - return &State{} -} - -// lua_touserdata -func (L *State) ToUserdata(index int) unsafe.Pointer { - return unsafe.Pointer(C.lua_touserdata(L.s, C.int(index))) -} - -// lua_type -func (L *State) Type(index int) LuaValType { - return LuaValType(C.lua_type(L.s, C.int(index))) -} - -// lua_typename -func (L *State) Typename(tp int) string { - return C.GoString(C.lua_typename(L.s, C.int(tp))) -} - -// lua_xmove -func XMove(from *State, to *State, n int) { - C.lua_xmove(from.s, to.s, C.int(n)) -} - -// Restricted library opens - -// Calls luaopen_base -func (L *State) OpenBase() { - C.clua_openbase(L.s) -} - -// Calls luaopen_io -func (L *State) OpenIO() { - C.clua_openio(L.s) -} - -// Calls luaopen_math -func (L *State) OpenMath() { - C.clua_openmath(L.s) -} - -// Calls luaopen_package -func (L *State) OpenPackage() { - C.clua_openpackage(L.s) -} - -// Calls luaopen_string -func (L *State) OpenString() { - C.clua_openstring(L.s) -} - -// Calls luaopen_table -func (L *State) OpenTable() { - C.clua_opentable(L.s) -} - -// Calls luaopen_os -func (L *State) OpenOS() { - C.clua_openos(L.s) -} - -// Sets the lua hook (lua_sethook). -// This and SetExecutionLimit are mutual exclusive -func (L *State) SetHook(f HookFunction, instrNumber int) { - L.hookFn = f - C.clua_sethook(L.s, C.int(instrNumber)) -} - -// Sets the maximum number of operations to execute at instrNumber, after this the execution ends -// This and SetHook are mutual exclusive -func (L *State) SetExecutionLimit(instrNumber int) { - L.SetHook(func(l *State) { - l.RaiseError(ExecutionQuantumExceeded) - }, instrNumber) -} - -// Returns the current stack trace -func (L *State) StackTrace() []LuaStackEntry { - r := []LuaStackEntry{} - var d C.lua_Debug - Sln := C.CString("Sln") - defer C.free(unsafe.Pointer(Sln)) - - for depth := 0; C.lua_getstack(L.s, C.int(depth), &d) > 0; depth++ { - C.lua_getinfo(L.s, Sln, &d) - ssb := make([]byte, C.LUA_IDSIZE) - for i := 0; i < C.LUA_IDSIZE; i++ { - ssb[i] = byte(d.short_src[i]) - if ssb[i] == 0 { - ssb = ssb[:i] - break - } - } - ss := string(ssb) - - r = append(r, LuaStackEntry{C.GoString(d.name), C.GoString(d.source), ss, int(d.currentline)}) - } - - return r -} - -func (L *State) RaiseError(msg string) { - st := L.StackTrace() - prefix := "" - if len(st) >= 2 { - prefix = fmt.Sprintf("%s:%d: ", st[1].ShortSource, st[1].CurrentLine) - } - panic(&LuaError{0, prefix + msg, st}) -} - -func (L *State) NewError(msg string) *LuaError { - return &LuaError{0, msg, L.StackTrace()} -} - -func (L *State) GetState() *C.lua_State { - return L.s -} diff --git a/lua/lua51/dummy.go b/lua/lua/dummy.go similarity index 100% rename from lua/lua51/dummy.go rename to lua/lua/dummy.go diff --git a/lua/lua51/lauxlib.h b/lua/lua/lauxlib.h similarity index 83% rename from lua/lua51/lauxlib.h rename to lua/lua/lauxlib.h index 3425823..a44f027 100644 --- a/lua/lua51/lauxlib.h +++ b/lua/lua/lauxlib.h @@ -15,31 +15,15 @@ #include "lua.h" -#if defined(LUA_COMPAT_GETN) -LUALIB_API int (luaL_getn) (lua_State *L, int t); -LUALIB_API void (luaL_setn) (lua_State *L, int t, int n); -#else -#define luaL_getn(L,i) ((int)lua_objlen(L, i)) -#define luaL_setn(L,i,j) ((void)0) /* no op! */ -#endif - -#if defined(LUA_COMPAT_OPENLIB) -#define luaI_openlib luaL_openlib -#endif - - /* extra error code for `luaL_load' */ #define LUA_ERRFILE (LUA_ERRERR+1) - typedef struct luaL_Reg { const char *name; lua_CFunction func; } luaL_Reg; - - -LUALIB_API void (luaI_openlib) (lua_State *L, const char *libname, +LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname, const luaL_Reg *l, int nup); LUALIB_API void (luaL_register) (lua_State *L, const char *libname, const luaL_Reg *l); @@ -71,6 +55,10 @@ LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def, const char *const lst[]); +/* pre-defined references */ +#define LUA_NOREF (-2) +#define LUA_REFNIL (-1) + LUALIB_API int (luaL_ref) (lua_State *L, int t); LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); @@ -88,7 +76,20 @@ LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx, const char *fname, int szhint); - +/* From Lua 5.2. */ +LUALIB_API int luaL_fileresult(lua_State *L, int stat, const char *fname); +LUALIB_API int luaL_execresult(lua_State *L, int stat); +LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, + const char *mode); +LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, + const char *name, const char *mode); +LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, + int level); +LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); +LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname, + int sizehint); +LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); +LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); /* @@ -118,6 +119,11 @@ LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx, #define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) +/* From Lua 5.2. */ +#define luaL_newlibtable(L, l) \ + lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) +#define luaL_newlib(L, l) (luaL_newlibtable(L, l), luaL_setfuncs(L, l, 0)) + /* ** {====================================================== ** Generic Buffer manipulation @@ -152,23 +158,4 @@ LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); /* }====================================================== */ - -/* compatibility with ref system */ - -/* pre-defined references */ -#define LUA_NOREF (-2) -#define LUA_REFNIL (-1) - -#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \ - (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0)) - -#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref)) - -#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref)) - - -#define luaL_reg luaL_Reg - #endif - - diff --git a/lua/lua/lj_arch.h b/lua/lua/lj_arch.h new file mode 100644 index 0000000..5851fb2 --- /dev/null +++ b/lua/lua/lj_arch.h @@ -0,0 +1,618 @@ +/* +** Target architecture selection. +** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h +*/ + +#ifndef _LJ_ARCH_H +#define _LJ_ARCH_H + +#include "lua.h" + +/* Target endianess. */ +#define LUAJIT_LE 0 +#define LUAJIT_BE 1 + +/* Target architectures. */ +#define LUAJIT_ARCH_X86 1 +#define LUAJIT_ARCH_x86 1 +#define LUAJIT_ARCH_X64 2 +#define LUAJIT_ARCH_x64 2 +#define LUAJIT_ARCH_ARM 3 +#define LUAJIT_ARCH_arm 3 +#define LUAJIT_ARCH_ARM64 4 +#define LUAJIT_ARCH_arm64 4 +#define LUAJIT_ARCH_PPC 5 +#define LUAJIT_ARCH_ppc 5 +#define LUAJIT_ARCH_MIPS 6 +#define LUAJIT_ARCH_mips 6 +#define LUAJIT_ARCH_MIPS32 6 +#define LUAJIT_ARCH_mips32 6 +#define LUAJIT_ARCH_MIPS64 7 +#define LUAJIT_ARCH_mips64 7 +#define LUAJIT_ARCH_S390X 8 +#define LUAJIT_ARCH_s390x 8 + +/* Target OS. */ +#define LUAJIT_OS_OTHER 0 +#define LUAJIT_OS_WINDOWS 1 +#define LUAJIT_OS_LINUX 2 +#define LUAJIT_OS_OSX 3 +#define LUAJIT_OS_BSD 4 +#define LUAJIT_OS_POSIX 5 + +/* Select native target if no target defined. */ +#ifndef LUAJIT_TARGET + +#if defined(__i386) || defined(__i386__) || defined(_M_IX86) +#define LUAJIT_TARGET LUAJIT_ARCH_X86 +#elif defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64) +#define LUAJIT_TARGET LUAJIT_ARCH_X64 +#elif defined(__arm__) || defined(__arm) || defined(__ARM__) || defined(__ARM) +#define LUAJIT_TARGET LUAJIT_ARCH_ARM +#elif defined(__aarch64__) +#define LUAJIT_TARGET LUAJIT_ARCH_ARM64 +#elif defined(__s390x__) || defined(__s390x) +#define LUAJIT_TARGET LUAJIT_ARCH_S390X +#elif defined(__ppc__) || defined(__ppc) || defined(__PPC__) || defined(__PPC) || defined(__powerpc__) || defined(__powerpc) || defined(__POWERPC__) || defined(__POWERPC) || defined(_M_PPC) +#define LUAJIT_TARGET LUAJIT_ARCH_PPC +#elif defined(__mips64__) || defined(__mips64) || defined(__MIPS64__) || defined(__MIPS64) +#define LUAJIT_TARGET LUAJIT_ARCH_MIPS64 +#elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(__MIPS) +#define LUAJIT_TARGET LUAJIT_ARCH_MIPS32 +#else +#error "No support for this architecture (yet)" +#endif + +#endif + +/* Select native OS if no target OS defined. */ +#ifndef LUAJIT_OS + +#if defined(_WIN32) && !defined(_XBOX_VER) +#define LUAJIT_OS LUAJIT_OS_WINDOWS +#elif defined(__linux__) +#define LUAJIT_OS LUAJIT_OS_LINUX +#elif defined(__MACH__) && defined(__APPLE__) +#define LUAJIT_OS LUAJIT_OS_OSX +#elif (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \ + defined(__NetBSD__) || defined(__OpenBSD__) || \ + defined(__DragonFly__)) && !defined(__ORBIS__) +#define LUAJIT_OS LUAJIT_OS_BSD +#elif (defined(__sun__) && defined(__svr4__)) || defined(__HAIKU__) +#define LUAJIT_OS LUAJIT_OS_POSIX +#elif defined(__CYGWIN__) +#define LJ_TARGET_CYGWIN 1 +#define LUAJIT_OS LUAJIT_OS_POSIX +#else +#define LUAJIT_OS LUAJIT_OS_OTHER +#endif + +#endif + +/* Set target OS properties. */ +#if LUAJIT_OS == LUAJIT_OS_WINDOWS +#define LJ_OS_NAME "Windows" +#elif LUAJIT_OS == LUAJIT_OS_LINUX +#define LJ_OS_NAME "Linux" +#elif LUAJIT_OS == LUAJIT_OS_OSX +#define LJ_OS_NAME "OSX" +#elif LUAJIT_OS == LUAJIT_OS_BSD +#define LJ_OS_NAME "BSD" +#elif LUAJIT_OS == LUAJIT_OS_POSIX +#define LJ_OS_NAME "POSIX" +#else +#define LJ_OS_NAME "Other" +#endif + +#define LJ_TARGET_WINDOWS (LUAJIT_OS == LUAJIT_OS_WINDOWS) +#define LJ_TARGET_LINUX (LUAJIT_OS == LUAJIT_OS_LINUX) +#define LJ_TARGET_OSX (LUAJIT_OS == LUAJIT_OS_OSX) +#define LJ_TARGET_IOS (LJ_TARGET_OSX && (LUAJIT_TARGET == LUAJIT_ARCH_ARM || LUAJIT_TARGET == LUAJIT_ARCH_ARM64)) +#define LJ_TARGET_POSIX (LUAJIT_OS > LUAJIT_OS_WINDOWS) +#define LJ_TARGET_DLOPEN LJ_TARGET_POSIX + +#ifdef __CELLOS_LV2__ +#define LJ_TARGET_PS3 1 +#define LJ_TARGET_CONSOLE 1 +#endif + +#ifdef __ORBIS__ +#define LJ_TARGET_PS4 1 +#define LJ_TARGET_CONSOLE 1 +#undef NULL +#define NULL ((void*)0) +#endif + +#ifdef __psp2__ +#define LJ_TARGET_PSVITA 1 +#define LJ_TARGET_CONSOLE 1 +#endif + +#if _XBOX_VER >= 200 +#define LJ_TARGET_XBOX360 1 +#define LJ_TARGET_CONSOLE 1 +#endif + +#ifdef _DURANGO +#define LJ_TARGET_XBOXONE 1 +#define LJ_TARGET_CONSOLE 1 +#define LJ_TARGET_GC64 1 +#endif + +#ifdef _UWP +#define LJ_TARGET_UWP 1 +#if LUAJIT_TARGET == LUAJIT_ARCH_X64 +#define LJ_TARGET_GC64 1 +#endif +#endif + +#define LJ_NUMMODE_SINGLE 0 /* Single-number mode only. */ +#define LJ_NUMMODE_SINGLE_DUAL 1 /* Default to single-number mode. */ +#define LJ_NUMMODE_DUAL 2 /* Dual-number mode only. */ +#define LJ_NUMMODE_DUAL_SINGLE 3 /* Default to dual-number mode. */ + +/* Set target architecture properties. */ +#if LUAJIT_TARGET == LUAJIT_ARCH_X86 + +#define LJ_ARCH_NAME "x86" +#define LJ_ARCH_BITS 32 +#define LJ_ARCH_ENDIAN LUAJIT_LE +#if LJ_TARGET_WINDOWS || LJ_TARGET_CYGWIN +#define LJ_ABI_WIN 1 +#else +#define LJ_ABI_WIN 0 +#endif +#define LJ_TARGET_X86 1 +#define LJ_TARGET_X86ORX64 1 +#define LJ_TARGET_EHRETREG 0 +#define LJ_TARGET_MASKSHIFT 1 +#define LJ_TARGET_MASKROT 1 +#define LJ_TARGET_UNALIGNED 1 +#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE_DUAL + +#elif LUAJIT_TARGET == LUAJIT_ARCH_X64 + +#define LJ_ARCH_NAME "x64" +#define LJ_ARCH_BITS 64 +#define LJ_ARCH_ENDIAN LUAJIT_LE +#if LJ_TARGET_WINDOWS || LJ_TARGET_CYGWIN +#define LJ_ABI_WIN 1 +#else +#define LJ_ABI_WIN 0 +#endif +#define LJ_TARGET_X64 1 +#define LJ_TARGET_X86ORX64 1 +#define LJ_TARGET_EHRETREG 0 +#define LJ_TARGET_JUMPRANGE 31 /* +-2^31 = +-2GB */ +#define LJ_TARGET_MASKSHIFT 1 +#define LJ_TARGET_MASKROT 1 +#define LJ_TARGET_UNALIGNED 1 +#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE_DUAL +#ifdef LUAJIT_ENABLE_GC64 +#define LJ_TARGET_GC64 1 +#endif + +#elif LUAJIT_TARGET == LUAJIT_ARCH_ARM + +#define LJ_ARCH_NAME "arm" +#define LJ_ARCH_BITS 32 +#define LJ_ARCH_ENDIAN LUAJIT_LE +#if !defined(LJ_ARCH_HASFPU) && __SOFTFP__ +#define LJ_ARCH_HASFPU 0 +#endif +#if !defined(LJ_ABI_SOFTFP) && !__ARM_PCS_VFP +#define LJ_ABI_SOFTFP 1 +#endif +#define LJ_ABI_EABI 1 +#define LJ_TARGET_ARM 1 +#define LJ_TARGET_EHRETREG 0 +#define LJ_TARGET_JUMPRANGE 25 /* +-2^25 = +-32MB */ +#define LJ_TARGET_MASKSHIFT 0 +#define LJ_TARGET_MASKROT 1 +#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */ +#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL + +#if __ARM_ARCH_8__ || __ARM_ARCH_8A__ +#define LJ_ARCH_VERSION 80 +#elif __ARM_ARCH_7__ || __ARM_ARCH_7A__ || __ARM_ARCH_7R__ || __ARM_ARCH_7S__ || __ARM_ARCH_7VE__ +#define LJ_ARCH_VERSION 70 +#elif __ARM_ARCH_6T2__ +#define LJ_ARCH_VERSION 61 +#elif __ARM_ARCH_6__ || __ARM_ARCH_6J__ || __ARM_ARCH_6K__ || __ARM_ARCH_6Z__ || __ARM_ARCH_6ZK__ +#define LJ_ARCH_VERSION 60 +#else +#define LJ_ARCH_VERSION 50 +#endif + +#elif LUAJIT_TARGET == LUAJIT_ARCH_ARM64 + +#define LJ_ARCH_BITS 64 +#if defined(__AARCH64EB__) +#define LJ_ARCH_NAME "arm64be" +#define LJ_ARCH_ENDIAN LUAJIT_BE +#else +#define LJ_ARCH_NAME "arm64" +#define LJ_ARCH_ENDIAN LUAJIT_LE +#endif +#define LJ_TARGET_ARM64 1 +#define LJ_TARGET_EHRETREG 0 +#define LJ_TARGET_JUMPRANGE 27 /* +-2^27 = +-128MB */ +#define LJ_TARGET_MASKSHIFT 1 +#define LJ_TARGET_MASKROT 1 +#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */ +#define LJ_TARGET_GC64 1 +#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL + +#define LJ_ARCH_VERSION 80 + +#elif LUAJIT_TARGET == LUAJIT_ARCH_PPC + +#ifndef LJ_ARCH_ENDIAN +#if __BYTE_ORDER__ != __ORDER_BIG_ENDIAN__ +#define LJ_ARCH_ENDIAN LUAJIT_LE +#else +#define LJ_ARCH_ENDIAN LUAJIT_BE +#endif +#endif + +#if _LP64 +#define LJ_ARCH_BITS 64 +#if LJ_ARCH_ENDIAN == LUAJIT_LE +#define LJ_ARCH_NAME "ppc64le" +#else +#define LJ_ARCH_NAME "ppc64" +#endif +#else +#define LJ_ARCH_BITS 32 +#define LJ_ARCH_NAME "ppc" + +#if !defined(LJ_ARCH_HASFPU) +#if defined(_SOFT_FLOAT) || defined(_SOFT_DOUBLE) +#define LJ_ARCH_HASFPU 0 +#else +#define LJ_ARCH_HASFPU 1 +#endif +#endif + +#if !defined(LJ_ABI_SOFTFP) +#if defined(_SOFT_FLOAT) || defined(_SOFT_DOUBLE) +#define LJ_ABI_SOFTFP 1 +#else +#define LJ_ABI_SOFTFP 0 +#endif +#endif +#endif + +#if LJ_ABI_SOFTFP +#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL +#else +#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL_SINGLE +#endif + +#define LJ_TARGET_PPC 1 +#define LJ_TARGET_EHRETREG 3 +#define LJ_TARGET_JUMPRANGE 25 /* +-2^25 = +-32MB */ +#define LJ_TARGET_MASKSHIFT 0 +#define LJ_TARGET_MASKROT 1 +#define LJ_TARGET_UNIFYROT 1 /* Want only IR_BROL. */ + +#if LJ_TARGET_CONSOLE +#define LJ_ARCH_PPC32ON64 1 +#define LJ_ARCH_NOFFI 1 +#elif LJ_ARCH_BITS == 64 +#define LJ_ARCH_PPC64 1 +#define LJ_TARGET_GC64 1 +#define LJ_ARCH_NOJIT 1 /* NYI */ +#endif + +#if _ARCH_PWR7 +#define LJ_ARCH_VERSION 70 +#elif _ARCH_PWR6 +#define LJ_ARCH_VERSION 60 +#elif _ARCH_PWR5X +#define LJ_ARCH_VERSION 51 +#elif _ARCH_PWR5 +#define LJ_ARCH_VERSION 50 +#elif _ARCH_PWR4 +#define LJ_ARCH_VERSION 40 +#else +#define LJ_ARCH_VERSION 0 +#endif +#if _ARCH_PPCSQ +#define LJ_ARCH_SQRT 1 +#endif +#if _ARCH_PWR5X +#define LJ_ARCH_ROUND 1 +#endif +#if __PPU__ +#define LJ_ARCH_CELL 1 +#endif +#if LJ_TARGET_XBOX360 +#define LJ_ARCH_XENON 1 +#endif + +#elif LUAJIT_TARGET == LUAJIT_ARCH_MIPS32 || LUAJIT_TARGET == LUAJIT_ARCH_MIPS64 + +#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) +#if LUAJIT_TARGET == LUAJIT_ARCH_MIPS32 +#define LJ_ARCH_NAME "mipsel" +#else +#define LJ_ARCH_NAME "mips64el" +#endif +#define LJ_ARCH_ENDIAN LUAJIT_LE +#else +#if LUAJIT_TARGET == LUAJIT_ARCH_MIPS32 +#define LJ_ARCH_NAME "mips" +#else +#define LJ_ARCH_NAME "mips64" +#endif +#define LJ_ARCH_ENDIAN LUAJIT_BE +#endif + +#if !defined(LJ_ARCH_HASFPU) +#ifdef __mips_soft_float +#define LJ_ARCH_HASFPU 0 +#else +#define LJ_ARCH_HASFPU 1 +#endif +#endif + +#if !defined(LJ_ABI_SOFTFP) +#ifdef __mips_soft_float +#define LJ_ABI_SOFTFP 1 +#else +#define LJ_ABI_SOFTFP 0 +#endif +#endif + +#if LUAJIT_TARGET == LUAJIT_ARCH_MIPS32 +#define LJ_ARCH_BITS 32 +#define LJ_TARGET_MIPS32 1 +#else +#define LJ_ARCH_BITS 64 +#define LJ_TARGET_MIPS64 1 +#define LJ_TARGET_GC64 1 +#endif +#define LJ_TARGET_MIPS 1 +#define LJ_TARGET_EHRETREG 4 +#define LJ_TARGET_JUMPRANGE 27 /* 2*2^27 = 256MB-aligned region */ +#define LJ_TARGET_MASKSHIFT 1 +#define LJ_TARGET_MASKROT 1 +#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */ +#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL + +#if _MIPS_ARCH_MIPS32R2 || _MIPS_ARCH_MIPS64R2 +#define LJ_ARCH_VERSION 20 +#else +#define LJ_ARCH_VERSION 10 +#endif + +#elif LUAJIT_TARGET == LUAJIT_ARCH_S390X + +#define LJ_ARCH_NAME "s390x" +#define LJ_ARCH_BITS 64 +#define LJ_ARCH_ENDIAN LUAJIT_BE +#define LJ_TARGET_S390X 1 +#define LJ_TARGET_EHRETREG 0xe +#define LJ_TARGET_JUMPRANGE 32 /* +-2^32 = +-4GB (32-bit, halfword aligned) */ +#define LJ_TARGET_MASKSHIFT 1 +#define LJ_TARGET_MASKROT 1 +#define LJ_TARGET_UNALIGNED 1 +#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL +#define LJ_TARGET_GC64 1 +#define LJ_ARCH_NOJIT 1 /* NYI */ + +#else +#error "No target architecture defined" +#endif + +#ifndef LJ_PAGESIZE +#define LJ_PAGESIZE 4096 +#endif + +/* Check for minimum required compiler versions. */ +#if defined(__GNUC__) +#if LJ_TARGET_X86 +#if (__GNUC__ < 3) || ((__GNUC__ == 3) && __GNUC_MINOR__ < 4) +#error "Need at least GCC 3.4 or newer" +#endif +#elif LJ_TARGET_X64 +#if 0 && __GNUC__ < 4 +#error "Need at least GCC 4.0 or newer" +#endif +#elif LJ_TARGET_ARM +#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 2) +#error "Need at least GCC 4.2 or newer" +#endif +#elif LJ_TARGET_ARM64 +#if __clang__ +#if ((__clang_major__ < 3) || ((__clang_major__ == 3) && __clang_minor__ < 5)) && !defined(__NX_TOOLCHAIN_MAJOR__) +#error "Need at least Clang 3.5 or newer" +#endif +#else +#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 8) +#error "Need at least GCC 4.8 or newer" +#endif +#endif +#elif !LJ_TARGET_PS3 +#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 3) +#error "Need at least GCC 4.3 or newer" +#endif +#endif +#endif + +/* Check target-specific constraints. */ +#ifndef _BUILDVM_H +#if LJ_TARGET_X64 +#if __USING_SJLJ_EXCEPTIONS__ +#error "Need a C compiler with native exception handling on x64" +#endif +#elif LJ_TARGET_ARM +#if defined(__ARMEB__) +#error "No support for big-endian ARM" +#endif +#if __ARM_ARCH_6M__ || __ARM_ARCH_7M__ || __ARM_ARCH_7EM__ +#error "No support for Cortex-M CPUs" +#endif +#if !(__ARM_EABI__ || LJ_TARGET_IOS) +#error "Only ARM EABI or iOS 3.0+ ABI is supported" +#endif +#elif LJ_TARGET_ARM64 +#if defined(_ILP32) +#error "No support for ILP32 model on ARM64" +#endif +#elif LJ_TARGET_PPC +#if !LJ_ARCH_PPC64 && (defined(_LITTLE_ENDIAN) && (!defined(_BYTE_ORDER) || (_BYTE_ORDER == _LITTLE_ENDIAN))) +#error "No support for little-endian PPC32" +#endif +#if defined(__NO_FPRS__) && !defined(_SOFT_FLOAT) +#error "No support for PPC/e500 anymore (use LuaJIT 2.0)" +#endif +#elif LJ_TARGET_MIPS32 +#if !((defined(_MIPS_SIM_ABI32) && _MIPS_SIM == _MIPS_SIM_ABI32) || (defined(_ABIO32) && _MIPS_SIM == _ABIO32)) +#error "Only o32 ABI supported for MIPS32" +#endif +#elif LJ_TARGET_MIPS64 +#if !((defined(_MIPS_SIM_ABI64) && _MIPS_SIM == _MIPS_SIM_ABI64) || (defined(_ABI64) && _MIPS_SIM == _ABI64)) +#error "Only n64 ABI supported for MIPS64" +#endif +#endif +#endif + +/* Enable or disable the dual-number mode for the VM. */ +#if (LJ_ARCH_NUMMODE == LJ_NUMMODE_SINGLE && LUAJIT_NUMMODE == 2) || \ + (LJ_ARCH_NUMMODE == LJ_NUMMODE_DUAL && LUAJIT_NUMMODE == 1) +#error "No support for this number mode on this architecture" +#endif +#if LJ_ARCH_NUMMODE == LJ_NUMMODE_DUAL || \ + (LJ_ARCH_NUMMODE == LJ_NUMMODE_DUAL_SINGLE && LUAJIT_NUMMODE != 1) || \ + (LJ_ARCH_NUMMODE == LJ_NUMMODE_SINGLE_DUAL && LUAJIT_NUMMODE == 2) +#define LJ_DUALNUM 1 +#else +#define LJ_DUALNUM 0 +#endif + +#if LJ_TARGET_IOS || LJ_TARGET_CONSOLE +/* Runtime code generation is restricted on iOS. Complain to Apple, not me. */ +/* Ditto for the consoles. Complain to Sony or MS, not me. */ +#ifndef LUAJIT_ENABLE_JIT +#define LJ_OS_NOJIT 1 +#endif +#endif + +/* 64 bit GC references. */ +#if LJ_TARGET_GC64 +#define LJ_GC64 1 +#else +#define LJ_GC64 0 +#endif + +/* 2-slot frame info. */ +#if LJ_GC64 +#define LJ_FR2 1 +#else +#define LJ_FR2 0 +#endif + +/* Disable or enable the JIT compiler. */ +#if defined(LUAJIT_DISABLE_JIT) || defined(LJ_ARCH_NOJIT) || defined(LJ_OS_NOJIT) +#define LJ_HASJIT 0 +#else +#define LJ_HASJIT 1 +#endif + +/* Disable or enable the FFI extension. */ +#if defined(LUAJIT_DISABLE_FFI) || defined(LJ_ARCH_NOFFI) +#define LJ_HASFFI 0 +#else +#define LJ_HASFFI 1 +#endif + +#if defined(LUAJIT_DISABLE_PROFILE) +#define LJ_HASPROFILE 0 +#elif LJ_TARGET_POSIX +#define LJ_HASPROFILE 1 +#define LJ_PROFILE_SIGPROF 1 +#elif LJ_TARGET_PS3 +#define LJ_HASPROFILE 1 +#define LJ_PROFILE_PTHREAD 1 +#elif LJ_TARGET_WINDOWS || LJ_TARGET_XBOX360 +#define LJ_HASPROFILE 1 +#define LJ_PROFILE_WTHREAD 1 +#else +#define LJ_HASPROFILE 0 +#endif + +#ifndef LJ_ARCH_HASFPU +#define LJ_ARCH_HASFPU 1 +#endif +#ifndef LJ_ABI_SOFTFP +#define LJ_ABI_SOFTFP 0 +#endif +#define LJ_SOFTFP (!LJ_ARCH_HASFPU) +#define LJ_SOFTFP32 (LJ_SOFTFP && LJ_32) + +#if LJ_ARCH_ENDIAN == LUAJIT_BE +#define LJ_LE 0 +#define LJ_BE 1 +#define LJ_ENDIAN_SELECT(le, be) be +#define LJ_ENDIAN_LOHI(lo, hi) hi lo +#else +#define LJ_LE 1 +#define LJ_BE 0 +#define LJ_ENDIAN_SELECT(le, be) le +#define LJ_ENDIAN_LOHI(lo, hi) lo hi +#endif + +#if LJ_ARCH_BITS == 32 +#define LJ_32 1 +#define LJ_64 0 +#else +#define LJ_32 0 +#define LJ_64 1 +#endif + +#ifndef LJ_TARGET_UNALIGNED +#define LJ_TARGET_UNALIGNED 0 +#endif + +/* Various workarounds for embedded operating systems or weak C runtimes. */ +#if defined(__ANDROID__) || defined(__symbian__) || LJ_TARGET_XBOX360 || LJ_TARGET_WINDOWS +#define LUAJIT_NO_LOG2 +#endif +#if defined(__symbian__) || LJ_TARGET_WINDOWS +#define LUAJIT_NO_EXP2 +#endif +#if LJ_TARGET_CONSOLE || (LJ_TARGET_IOS && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0) +#define LJ_NO_SYSTEM 1 +#endif + +#if !defined(LUAJIT_NO_UNWIND) && __GNU_COMPACT_EH__ +/* NYI: no support for compact unwind specification, yet. */ +#define LUAJIT_NO_UNWIND 1 +#endif + +#if defined(LUAJIT_NO_UNWIND) || defined(__symbian__) || LJ_TARGET_IOS || LJ_TARGET_PS3 || LJ_TARGET_PS4 +#define LJ_NO_UNWIND 1 +#endif + +#if LJ_TARGET_WINDOWS +#if LJ_TARGET_UWP +#define LJ_WIN_VALLOC VirtualAllocFromApp +#define LJ_WIN_VPROTECT VirtualProtectFromApp +extern void *LJ_WIN_LOADLIBA(const char *path); +#else +#define LJ_WIN_VALLOC VirtualAlloc +#define LJ_WIN_VPROTECT VirtualProtect +#define LJ_WIN_LOADLIBA(path) LoadLibraryExA((path), NULL, 0) +#endif +#endif + +/* Compatibility with Lua 5.1 vs. 5.2. */ +#ifdef LUAJIT_ENABLE_LUA52COMPAT +#define LJ_52 1 +#else +#define LJ_52 0 +#endif + +#endif diff --git a/lua/lua/lj_def.h b/lua/lua/lj_def.h new file mode 100644 index 0000000..fd41cb1 --- /dev/null +++ b/lua/lua/lj_def.h @@ -0,0 +1,361 @@ +/* +** LuaJIT common internal definitions. +** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h +*/ + +#ifndef _LJ_DEF_H +#define _LJ_DEF_H + +#include "lua.h" + +#if defined(_MSC_VER) +/* MSVC is stuck in the last century and doesn't have C99's stdint.h. */ +typedef __int8 int8_t; +typedef __int16 int16_t; +typedef __int32 int32_t; +typedef __int64 int64_t; +typedef unsigned __int8 uint8_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int32 uint32_t; +typedef unsigned __int64 uint64_t; +#ifdef _WIN64 +typedef __int64 intptr_t; +typedef unsigned __int64 uintptr_t; +#else +typedef __int32 intptr_t; +typedef unsigned __int32 uintptr_t; +#endif +#elif defined(__symbian__) +/* Cough. */ +typedef signed char int8_t; +typedef short int int16_t; +typedef int int32_t; +typedef long long int64_t; +typedef unsigned char uint8_t; +typedef unsigned short int uint16_t; +typedef unsigned int uint32_t; +typedef unsigned long long uint64_t; +typedef int intptr_t; +typedef unsigned int uintptr_t; +#else +#include +#endif + +/* Needed everywhere. */ +#include +#include + +/* Various VM limits. */ +#define LJ_MAX_MEM32 0x7fffff00 /* Max. 32 bit memory allocation. */ +#define LJ_MAX_MEM64 ((uint64_t)1<<47) /* Max. 64 bit memory allocation. */ +/* Max. total memory allocation. */ +#define LJ_MAX_MEM (LJ_GC64 ? LJ_MAX_MEM64 : LJ_MAX_MEM32) +#define LJ_MAX_ALLOC LJ_MAX_MEM /* Max. individual allocation length. */ +#define LJ_MAX_STR LJ_MAX_MEM32 /* Max. string length. */ +#define LJ_MAX_BUF LJ_MAX_MEM32 /* Max. buffer length. */ +#define LJ_MAX_UDATA LJ_MAX_MEM32 /* Max. userdata length. */ + +#define LJ_MAX_STRTAB (1<<26) /* Max. string table size. */ +#define LJ_MAX_HBITS 26 /* Max. hash bits. */ +#define LJ_MAX_ABITS 28 /* Max. bits of array key. */ +#define LJ_MAX_ASIZE ((1<<(LJ_MAX_ABITS-1))+1) /* Max. array part size. */ +#define LJ_MAX_COLOSIZE 16 /* Max. elems for colocated array. */ + +#define LJ_MAX_LINE LJ_MAX_MEM32 /* Max. source code line number. */ +#define LJ_MAX_XLEVEL 200 /* Max. syntactic nesting level. */ +#define LJ_MAX_BCINS (1<<26) /* Max. # of bytecode instructions. */ +#define LJ_MAX_SLOTS 250 /* Max. # of slots in a Lua func. */ +#define LJ_MAX_LOCVAR 200 /* Max. # of local variables. */ +#define LJ_MAX_UPVAL 120 /* Max. # of upvalues. */ + +#define LJ_MAX_IDXCHAIN 100 /* __index/__newindex chain limit. */ +#define LJ_STACK_EXTRA (5+2*LJ_FR2) /* Extra stack space (metamethods). */ + +#define LJ_NUM_CBPAGE 1 /* Number of FFI callback pages. */ + +/* Minimum table/buffer sizes. */ +#define LJ_MIN_GLOBAL 6 /* Min. global table size (hbits). */ +#define LJ_MIN_REGISTRY 2 /* Min. registry size (hbits). */ +#define LJ_MIN_STRTAB 256 /* Min. string table size (pow2). */ +#define LJ_MIN_SBUF 32 /* Min. string buffer length. */ +#define LJ_MIN_VECSZ 8 /* Min. size for growable vectors. */ +#define LJ_MIN_IRSZ 32 /* Min. size for growable IR. */ + +/* JIT compiler limits. */ +#define LJ_MAX_JSLOTS 250 /* Max. # of stack slots for a trace. */ +#define LJ_MAX_PHI 64 /* Max. # of PHIs for a loop. */ +#define LJ_MAX_EXITSTUBGR 16 /* Max. # of exit stub groups. */ + +/* Various macros. */ +#ifndef UNUSED +#define UNUSED(x) ((void)(x)) /* to avoid warnings */ +#endif + +#define U64x(hi, lo) (((uint64_t)0x##hi << 32) + (uint64_t)0x##lo) +#define i32ptr(p) ((int32_t)(intptr_t)(void *)(p)) +#define u32ptr(p) ((uint32_t)(intptr_t)(void *)(p)) +#define i64ptr(p) ((int64_t)(intptr_t)(void *)(p)) +#define u64ptr(p) ((uint64_t)(intptr_t)(void *)(p)) +#define igcptr(p) (LJ_GC64 ? i64ptr(p) : i32ptr(p)) + +#define checki8(x) ((x) == (int32_t)(int8_t)(x)) +#define checku8(x) ((x) == (int32_t)(uint8_t)(x)) +#define checki16(x) ((x) == (int32_t)(int16_t)(x)) +#define checku16(x) ((x) == (int32_t)(uint16_t)(x)) +#define checki32(x) ((x) == (int32_t)(x)) +#define checku32(x) ((x) == (uint32_t)(x)) +#define checkptr32(x) ((uintptr_t)(x) == (uint32_t)(uintptr_t)(x)) +#define checkptr47(x) (((uint64_t)(uintptr_t)(x) >> 47) == 0) +#define checkptrGC(x) (LJ_GC64 ? checkptr47((x)) : LJ_64 ? checkptr32((x)) :1) + +/* Every half-decent C compiler transforms this into a rotate instruction. */ +#define lj_rol(x, n) (((x)<<(n)) | ((x)>>(-(int)(n)&(8*sizeof(x)-1)))) +#define lj_ror(x, n) (((x)<<(-(int)(n)&(8*sizeof(x)-1))) | ((x)>>(n))) + +/* A really naive Bloom filter. But sufficient for our needs. */ +typedef uintptr_t BloomFilter; +#define BLOOM_MASK (8*sizeof(BloomFilter) - 1) +#define bloombit(x) ((uintptr_t)1 << ((x) & BLOOM_MASK)) +#define bloomset(b, x) ((b) |= bloombit((x))) +#define bloomtest(b, x) ((b) & bloombit((x))) + +#if defined(__GNUC__) || defined(__psp2__) + +#define LJ_NORET __attribute__((noreturn)) +#define LJ_ALIGN(n) __attribute__((aligned(n))) +#define LJ_INLINE inline +#define LJ_AINLINE inline __attribute__((always_inline)) +#define LJ_NOINLINE __attribute__((noinline)) + +#if defined(__ELF__) || defined(__MACH__) || defined(__psp2__) +#if !((defined(__sun__) && defined(__svr4__)) || defined(__CELLOS_LV2__)) +#define LJ_NOAPI extern __attribute__((visibility("hidden"))) +#endif +#endif + +/* Note: it's only beneficial to use fastcall on x86 and then only for up to +** two non-FP args. The amalgamated compile covers all LJ_FUNC cases. Only +** indirect calls and related tail-called C functions are marked as fastcall. +*/ +#if defined(__i386__) +#define LJ_FASTCALL __attribute__((fastcall)) +#endif + +#define LJ_LIKELY(x) __builtin_expect(!!(x), 1) +#define LJ_UNLIKELY(x) __builtin_expect(!!(x), 0) + +#define lj_ffs(x) ((uint32_t)__builtin_ctz(x)) +/* Don't ask ... */ +#if defined(__INTEL_COMPILER) && (defined(__i386__) || defined(__x86_64__)) +static LJ_AINLINE uint32_t lj_fls(uint32_t x) +{ + uint32_t r; __asm__("bsrl %1, %0" : "=r" (r) : "rm" (x) : "cc"); return r; +} +#else +#define lj_fls(x) ((uint32_t)(__builtin_clz(x)^31)) +#endif + +#if defined(__arm__) +static LJ_AINLINE uint32_t lj_bswap(uint32_t x) +{ +#if defined(__psp2__) + return __builtin_rev(x); +#else + uint32_t r; +#if __ARM_ARCH_6__ || __ARM_ARCH_6J__ || __ARM_ARCH_6T2__ || __ARM_ARCH_6Z__ ||\ + __ARM_ARCH_6ZK__ || __ARM_ARCH_7__ || __ARM_ARCH_7A__ || __ARM_ARCH_7R__ + __asm__("rev %0, %1" : "=r" (r) : "r" (x)); + return r; +#else +#ifdef __thumb__ + r = x ^ lj_ror(x, 16); +#else + __asm__("eor %0, %1, %1, ror #16" : "=r" (r) : "r" (x)); +#endif + return ((r & 0xff00ffffu) >> 8) ^ lj_ror(x, 8); +#endif +#endif +} + +static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) +{ + return ((uint64_t)lj_bswap((uint32_t)x)<<32) | lj_bswap((uint32_t)(x>>32)); +} +#elif (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) +static LJ_AINLINE uint32_t lj_bswap(uint32_t x) +{ + return (uint32_t)__builtin_bswap32((int32_t)x); +} + +static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) +{ + return (uint64_t)__builtin_bswap64((int64_t)x); +} +#elif defined(__i386__) || defined(__x86_64__) +static LJ_AINLINE uint32_t lj_bswap(uint32_t x) +{ + uint32_t r; __asm__("bswap %0" : "=r" (r) : "0" (x)); return r; +} + +#if defined(__i386__) +static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) +{ + return ((uint64_t)lj_bswap((uint32_t)x)<<32) | lj_bswap((uint32_t)(x>>32)); +} +#else +static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) +{ + uint64_t r; __asm__("bswap %0" : "=r" (r) : "0" (x)); return r; +} +#endif +#else +static LJ_AINLINE uint32_t lj_bswap(uint32_t x) +{ + return (x << 24) | ((x & 0xff00) << 8) | ((x >> 8) & 0xff00) | (x >> 24); +} + +static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) +{ + return (uint64_t)lj_bswap((uint32_t)(x >> 32)) | + ((uint64_t)lj_bswap((uint32_t)x) << 32); +} +#endif + +typedef union __attribute__((packed)) Unaligned16 { + uint16_t u; + uint8_t b[2]; +} Unaligned16; + +typedef union __attribute__((packed)) Unaligned32 { + uint32_t u; + uint8_t b[4]; +} Unaligned32; + +/* Unaligned load of uint16_t. */ +static LJ_AINLINE uint16_t lj_getu16(const void *p) +{ + return ((const Unaligned16 *)p)->u; +} + +/* Unaligned load of uint32_t. */ +static LJ_AINLINE uint32_t lj_getu32(const void *p) +{ + return ((const Unaligned32 *)p)->u; +} + +#elif defined(_MSC_VER) + +#define LJ_NORET __declspec(noreturn) +#define LJ_ALIGN(n) __declspec(align(n)) +#define LJ_INLINE __inline +#define LJ_AINLINE __forceinline +#define LJ_NOINLINE __declspec(noinline) +#if defined(_M_IX86) +#define LJ_FASTCALL __fastcall +#endif + +#ifdef _M_PPC +unsigned int _CountLeadingZeros(long); +#pragma intrinsic(_CountLeadingZeros) +static LJ_AINLINE uint32_t lj_fls(uint32_t x) +{ + return _CountLeadingZeros(x) ^ 31; +} +#else +unsigned char _BitScanForward(uint32_t *, unsigned long); +unsigned char _BitScanReverse(uint32_t *, unsigned long); +#pragma intrinsic(_BitScanForward) +#pragma intrinsic(_BitScanReverse) + +static LJ_AINLINE uint32_t lj_ffs(uint32_t x) +{ + uint32_t r; _BitScanForward(&r, x); return r; +} + +static LJ_AINLINE uint32_t lj_fls(uint32_t x) +{ + uint32_t r; _BitScanReverse(&r, x); return r; +} +#endif + +unsigned long _byteswap_ulong(unsigned long); +uint64_t _byteswap_uint64(uint64_t); +#define lj_bswap(x) (_byteswap_ulong((x))) +#define lj_bswap64(x) (_byteswap_uint64((x))) + +#if defined(_M_PPC) && defined(LUAJIT_NO_UNALIGNED) +/* +** Replacement for unaligned loads on Xbox 360. Disabled by default since it's +** usually more costly than the occasional stall when crossing a cache-line. +*/ +static LJ_AINLINE uint16_t lj_getu16(const void *v) +{ + const uint8_t *p = (const uint8_t *)v; + return (uint16_t)((p[0]<<8) | p[1]); +} +static LJ_AINLINE uint32_t lj_getu32(const void *v) +{ + const uint8_t *p = (const uint8_t *)v; + return (uint32_t)((p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]); +} +#else +/* Unaligned loads are generally ok on x86/x64. */ +#define lj_getu16(p) (*(uint16_t *)(p)) +#define lj_getu32(p) (*(uint32_t *)(p)) +#endif + +#else +#error "missing defines for your compiler" +#endif + +/* Optional defines. */ +#ifndef LJ_FASTCALL +#define LJ_FASTCALL +#endif +#ifndef LJ_NORET +#define LJ_NORET +#endif +#ifndef LJ_NOAPI +#define LJ_NOAPI extern +#endif +#ifndef LJ_LIKELY +#define LJ_LIKELY(x) (x) +#define LJ_UNLIKELY(x) (x) +#endif + +/* Attributes for internal functions. */ +#define LJ_DATA LJ_NOAPI +#define LJ_DATADEF +#define LJ_ASMF LJ_NOAPI +#define LJ_FUNCA LJ_NOAPI +#if defined(ljamalg_c) +#define LJ_FUNC static +#else +#define LJ_FUNC LJ_NOAPI +#endif +#define LJ_FUNC_NORET LJ_FUNC LJ_NORET +#define LJ_FUNCA_NORET LJ_FUNCA LJ_NORET +#define LJ_ASMF_NORET LJ_ASMF LJ_NORET + +/* Runtime assertions. */ +#ifdef lua_assert +#define check_exp(c, e) (lua_assert(c), (e)) +#define api_check(l, e) lua_assert(e) +#else +#define lua_assert(c) ((void)0) +#define check_exp(c, e) (e) +#define api_check luai_apicheck +#endif + +/* Static assertions. */ +#define LJ_ASSERT_NAME2(name, line) name ## line +#define LJ_ASSERT_NAME(line) LJ_ASSERT_NAME2(lj_assert_, line) +#ifdef __COUNTER__ +#define LJ_STATIC_ASSERT(cond) \ + extern void LJ_ASSERT_NAME(__COUNTER__)(int STATIC_ASSERTION_FAILED[(cond)?1:-1]) +#else +#define LJ_STATIC_ASSERT(cond) \ + extern void LJ_ASSERT_NAME(__LINE__)(int STATIC_ASSERTION_FAILED[(cond)?1:-1]) +#endif + +#endif diff --git a/lua/lua/lj_obj.h b/lua/lua/lj_obj.h new file mode 100644 index 0000000..a89ea0d --- /dev/null +++ b/lua/lua/lj_obj.h @@ -0,0 +1,997 @@ +/* +** LuaJIT VM tags, values and objects. +** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h +** +** Portions taken verbatim or adapted from the Lua interpreter. +** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h +*/ + +#ifndef _LJ_OBJ_H +#define _LJ_OBJ_H + +#include "lua.h" +#include "lj_def.h" +#include "lj_arch.h" + +/* -- Memory references (32 bit address space) ---------------------------- */ + +/* Memory and GC object sizes. */ +typedef uint32_t MSize; +#if LJ_GC64 +typedef uint64_t GCSize; +#else +typedef uint32_t GCSize; +#endif + +/* Memory reference */ +typedef struct MRef { +#if LJ_GC64 + uint64_t ptr64; /* True 64 bit pointer. */ +#else + uint32_t ptr32; /* Pseudo 32 bit pointer. */ +#endif +} MRef; + +#if LJ_GC64 +#define mref(r, t) ((t *)(void *)(r).ptr64) + +#define setmref(r, p) ((r).ptr64 = (uint64_t)(void *)(p)) +#define setmrefr(r, v) ((r).ptr64 = (v).ptr64) +#else +#define mref(r, t) ((t *)(void *)(uintptr_t)(r).ptr32) + +#define setmref(r, p) ((r).ptr32 = (uint32_t)(uintptr_t)(void *)(p)) +#define setmrefr(r, v) ((r).ptr32 = (v).ptr32) +#endif + +/* -- GC object references (32 bit address space) ------------------------- */ + +/* GCobj reference */ +typedef struct GCRef { +#if LJ_GC64 + uint64_t gcptr64; /* True 64 bit pointer. */ +#else + uint32_t gcptr32; /* Pseudo 32 bit pointer. */ +#endif +} GCRef; + +/* Common GC header for all collectable objects. */ +#define GCHeader GCRef nextgc; uint8_t marked; uint8_t gct +/* This occupies 6 bytes, so use the next 2 bytes for non-32 bit fields. */ + +#if LJ_GC64 +#define gcref(r) ((GCobj *)(r).gcptr64) +#define gcrefp(r, t) ((t *)(void *)(r).gcptr64) +#define gcrefu(r) ((r).gcptr64) +#define gcrefeq(r1, r2) ((r1).gcptr64 == (r2).gcptr64) + +#define setgcref(r, gc) ((r).gcptr64 = (uint64_t)&(gc)->gch) +#define setgcreft(r, gc, it) \ + (r).gcptr64 = (uint64_t)&(gc)->gch | (((uint64_t)(it)) << 47) +#define setgcrefp(r, p) ((r).gcptr64 = (uint64_t)(p)) +#define setgcrefnull(r) ((r).gcptr64 = 0) +#define setgcrefr(r, v) ((r).gcptr64 = (v).gcptr64) +#else +#define gcref(r) ((GCobj *)(uintptr_t)(r).gcptr32) +#define gcrefp(r, t) ((t *)(void *)(uintptr_t)(r).gcptr32) +#define gcrefu(r) ((r).gcptr32) +#define gcrefeq(r1, r2) ((r1).gcptr32 == (r2).gcptr32) + +#define setgcref(r, gc) ((r).gcptr32 = (uint32_t)(uintptr_t)&(gc)->gch) +#define setgcrefp(r, p) ((r).gcptr32 = (uint32_t)(uintptr_t)(p)) +#define setgcrefnull(r) ((r).gcptr32 = 0) +#define setgcrefr(r, v) ((r).gcptr32 = (v).gcptr32) +#endif + +#define gcnext(gc) (gcref((gc)->gch.nextgc)) + +/* IMPORTANT NOTE: +** +** All uses of the setgcref* macros MUST be accompanied with a write barrier. +** +** This is to ensure the integrity of the incremental GC. The invariant +** to preserve is that a black object never points to a white object. +** I.e. never store a white object into a field of a black object. +** +** It's ok to LEAVE OUT the write barrier ONLY in the following cases: +** - The source is not a GC object (NULL). +** - The target is a GC root. I.e. everything in global_State. +** - The target is a lua_State field (threads are never black). +** - The target is a stack slot, see setgcV et al. +** - The target is an open upvalue, i.e. pointing to a stack slot. +** - The target is a newly created object (i.e. marked white). But make +** sure nothing invokes the GC inbetween. +** - The target and the source are the same object (self-reference). +** - The target already contains the object (e.g. moving elements around). +** +** The most common case is a store to a stack slot. All other cases where +** a barrier has been omitted are annotated with a NOBARRIER comment. +** +** The same logic applies for stores to table slots (array part or hash +** part). ALL uses of lj_tab_set* require a barrier for the stored value +** *and* the stored key, based on the above rules. In practice this means +** a barrier is needed if *either* of the key or value are a GC object. +** +** It's ok to LEAVE OUT the write barrier in the following special cases: +** - The stored value is nil. The key doesn't matter because it's either +** not resurrected or lj_tab_newkey() will take care of the key barrier. +** - The key doesn't matter if the *previously* stored value is guaranteed +** to be non-nil (because the key is kept alive in the table). +** - The key doesn't matter if it's guaranteed not to be part of the table, +** since lj_tab_newkey() takes care of the key barrier. This applies +** trivially to new tables, but watch out for resurrected keys. Storing +** a nil value leaves the key in the table! +** +** In case of doubt use lj_gc_anybarriert() as it's rather cheap. It's used +** by the interpreter for all table stores. +** +** Note: In contrast to Lua's GC, LuaJIT's GC does *not* specially mark +** dead keys in tables. The reference is left in, but it's guaranteed to +** be never dereferenced as long as the value is nil. It's ok if the key is +** freed or if any object subsequently gets the same address. +** +** Not destroying dead keys helps to keep key hash slots stable. This avoids +** specialization back-off for HREFK when a value flips between nil and +** non-nil and the GC gets in the way. It also allows safely hoisting +** HREF/HREFK across GC steps. Dead keys are only removed if a table is +** resized (i.e. by NEWREF) and xREF must not be CSEd across a resize. +** +** The trade-off is that a write barrier for tables must take the key into +** account, too. Implicitly resurrecting the key by storing a non-nil value +** may invalidate the incremental GC invariant. +*/ + +/* -- Common type definitions --------------------------------------------- */ + +/* Types for handling bytecodes. Need this here, details in lj_bc.h. */ +typedef uint32_t BCIns; /* Bytecode instruction. */ +typedef uint32_t BCPos; /* Bytecode position. */ +typedef uint32_t BCReg; /* Bytecode register. */ +typedef int32_t BCLine; /* Bytecode line number. */ + +/* Internal assembler functions. Never call these directly from C. */ +typedef void (*ASMFunction)(void); + +/* Resizable string buffer. Need this here, details in lj_buf.h. */ +typedef struct SBuf { + MRef p; /* String buffer pointer. */ + MRef e; /* String buffer end pointer. */ + MRef b; /* String buffer base. */ + MRef L; /* lua_State, used for buffer resizing. */ +} SBuf; + +/* -- Tags and values ----------------------------------------------------- */ + +/* Frame link. */ +typedef union { + int32_t ftsz; /* Frame type and size of previous frame. */ + MRef pcr; /* Or PC for Lua frames. */ +} FrameLink; + +/* Tagged value. */ +typedef LJ_ALIGN(8) union TValue { + uint64_t u64; /* 64 bit pattern overlaps number. */ + lua_Number n; /* Number object overlaps split tag/value object. */ +#if LJ_GC64 + GCRef gcr; /* GCobj reference with tag. */ + int64_t it64; + struct { + LJ_ENDIAN_LOHI( + int32_t i; /* Integer value. */ + , uint32_t it; /* Internal object tag. Must overlap MSW of number. */ + ) + }; +#else + struct { + LJ_ENDIAN_LOHI( + union { + GCRef gcr; /* GCobj reference (if any). */ + int32_t i; /* Integer value. */ + }; + , uint32_t it; /* Internal object tag. Must overlap MSW of number. */ + ) + }; +#endif +#if LJ_FR2 + int64_t ftsz; /* Frame type and size of previous frame, or PC. */ +#else + struct { + LJ_ENDIAN_LOHI( + GCRef func; /* Function for next frame (or dummy L). */ + , FrameLink tp; /* Link to previous frame. */ + ) + } fr; +#endif + struct { + LJ_ENDIAN_LOHI( + uint32_t lo; /* Lower 32 bits of number. */ + , uint32_t hi; /* Upper 32 bits of number. */ + ) + } u32; +} TValue; + +typedef const TValue cTValue; + +#define tvref(r) (mref(r, TValue)) + +/* More external and GCobj tags for internal objects. */ +#define LAST_TT LUA_TTHREAD +#define LUA_TPROTO (LAST_TT+1) +#define LUA_TCDATA (LAST_TT+2) + +/* Internal object tags. +** +** Format for 32 bit GC references (!LJ_GC64): +** +** Internal tags overlap the MSW of a number object (must be a double). +** Interpreted as a double these are special NaNs. The FPU only generates +** one type of NaN (0xfff8_0000_0000_0000). So MSWs > 0xfff80000 are available +** for use as internal tags. Small negative numbers are used to shorten the +** encoding of type comparisons (reg/mem against sign-ext. 8 bit immediate). +** +** ---MSW---.---LSW--- +** primitive types | itype | | +** lightuserdata | itype | void * | (32 bit platforms) +** lightuserdata |ffff| void * | (64 bit platforms, 47 bit pointers) +** GC objects | itype | GCRef | +** int (LJ_DUALNUM)| itype | int | +** number -------double------ +** +** Format for 64 bit GC references (LJ_GC64): +** +** The upper 13 bits must be 1 (0xfff8...) for a special NaN. The next +** 4 bits hold the internal tag. The lowest 47 bits either hold a pointer, +** a zero-extended 32 bit integer or all bits set to 1 for primitive types. +** +** ------MSW------.------LSW------ +** primitive types |1..1|itype|1..................1| +** GC objects/lightud |1..1|itype|-------GCRef--------| +** int (LJ_DUALNUM) |1..1|itype|0..0|-----int-------| +** number ------------double------------- +** +** ORDER LJ_T +** Primitive types nil/false/true must be first, lightuserdata next. +** GC objects are at the end, table/userdata must be lowest. +** Also check lj_ir.h for similar ordering constraints. +*/ +#define LJ_TNIL (~0u) +#define LJ_TFALSE (~1u) +#define LJ_TTRUE (~2u) +#define LJ_TLIGHTUD (~3u) +#define LJ_TSTR (~4u) +#define LJ_TUPVAL (~5u) +#define LJ_TTHREAD (~6u) +#define LJ_TPROTO (~7u) +#define LJ_TFUNC (~8u) +#define LJ_TTRACE (~9u) +#define LJ_TCDATA (~10u) +#define LJ_TTAB (~11u) +#define LJ_TUDATA (~12u) +/* This is just the canonical number type used in some places. */ +#define LJ_TNUMX (~13u) + +/* Integers have itype == LJ_TISNUM doubles have itype < LJ_TISNUM */ +#if LJ_64 && !LJ_GC64 +#define LJ_TISNUM 0xfffeffffu +#else +#define LJ_TISNUM LJ_TNUMX +#endif +#define LJ_TISTRUECOND LJ_TFALSE +#define LJ_TISPRI LJ_TTRUE +#define LJ_TISGCV (LJ_TSTR+1) +#define LJ_TISTABUD LJ_TTAB + +#if LJ_GC64 +#define LJ_GCVMASK (((uint64_t)1 << 47) - 1) +#endif + +/* -- String object ------------------------------------------------------- */ + +/* String object header. String payload follows. */ +typedef struct GCstr { + GCHeader; + uint8_t reserved; /* Used by lexer for fast lookup of reserved words. */ + uint8_t unused; + MSize hash; /* Hash of string. */ + MSize len; /* Size of string. */ +} GCstr; + +#define strref(r) (&gcref((r))->str) +#define strdata(s) ((const char *)((s)+1)) +#define strdatawr(s) ((char *)((s)+1)) +#define strVdata(o) strdata(strV(o)) +#define sizestring(s) (sizeof(struct GCstr)+(s)->len+1) + +/* -- Userdata object ----------------------------------------------------- */ + +/* Userdata object. Payload follows. */ +typedef struct GCudata { + GCHeader; + uint8_t udtype; /* Userdata type. */ + uint8_t unused2; + GCRef env; /* Should be at same offset in GCfunc. */ + MSize len; /* Size of payload. */ + GCRef metatable; /* Must be at same offset in GCtab. */ + uint32_t align1; /* To force 8 byte alignment of the payload. */ +} GCudata; + +/* Userdata types. */ +enum { + UDTYPE_USERDATA, /* Regular userdata. */ + UDTYPE_IO_FILE, /* I/O library FILE. */ + UDTYPE_FFI_CLIB, /* FFI C library namespace. */ + UDTYPE__MAX +}; + +#define uddata(u) ((void *)((u)+1)) +#define sizeudata(u) (sizeof(struct GCudata)+(u)->len) + +/* -- C data object ------------------------------------------------------- */ + +/* C data object. Payload follows. */ +typedef struct GCcdata { + GCHeader; + uint16_t ctypeid; /* C type ID. */ +} GCcdata; + +/* Prepended to variable-sized or realigned C data objects. */ +typedef struct GCcdataVar { + uint16_t offset; /* Offset to allocated memory (relative to GCcdata). */ + uint16_t extra; /* Extra space allocated (incl. GCcdata + GCcdatav). */ + MSize len; /* Size of payload. */ +} GCcdataVar; + +#define cdataptr(cd) ((void *)((cd)+1)) +#define cdataisv(cd) ((cd)->marked & 0x80) +#define cdatav(cd) ((GCcdataVar *)((char *)(cd) - sizeof(GCcdataVar))) +#define cdatavlen(cd) check_exp(cdataisv(cd), cdatav(cd)->len) +#define sizecdatav(cd) (cdatavlen(cd) + cdatav(cd)->extra) +#define memcdatav(cd) ((void *)((char *)(cd) - cdatav(cd)->offset)) + +/* -- Prototype object ---------------------------------------------------- */ + +#define SCALE_NUM_GCO ((int32_t)sizeof(lua_Number)/sizeof(GCRef)) +#define round_nkgc(n) (((n) + SCALE_NUM_GCO-1) & ~(SCALE_NUM_GCO-1)) + +typedef struct GCproto { + GCHeader; + uint8_t numparams; /* Number of parameters. */ + uint8_t framesize; /* Fixed frame size. */ + MSize sizebc; /* Number of bytecode instructions. */ +#if LJ_GC64 + uint32_t unused_gc64; +#endif + GCRef gclist; + MRef k; /* Split constant array (points to the middle). */ + MRef uv; /* Upvalue list. local slot|0x8000 or parent uv idx. */ + MSize sizekgc; /* Number of collectable constants. */ + MSize sizekn; /* Number of lua_Number constants. */ + MSize sizept; /* Total size including colocated arrays. */ + uint8_t sizeuv; /* Number of upvalues. */ + uint8_t flags; /* Miscellaneous flags (see below). */ + uint16_t trace; /* Anchor for chain of root traces. */ + /* ------ The following fields are for debugging/tracebacks only ------ */ + GCRef chunkname; /* Name of the chunk this function was defined in. */ + BCLine firstline; /* First line of the function definition. */ + BCLine numline; /* Number of lines for the function definition. */ + MRef lineinfo; /* Compressed map from bytecode ins. to source line. */ + MRef uvinfo; /* Upvalue names. */ + MRef varinfo; /* Names and compressed extents of local variables. */ +} GCproto; + +/* Flags for prototype. */ +#define PROTO_CHILD 0x01 /* Has child prototypes. */ +#define PROTO_VARARG 0x02 /* Vararg function. */ +#define PROTO_FFI 0x04 /* Uses BC_KCDATA for FFI datatypes. */ +#define PROTO_NOJIT 0x08 /* JIT disabled for this function. */ +#define PROTO_ILOOP 0x10 /* Patched bytecode with ILOOP etc. */ +/* Only used during parsing. */ +#define PROTO_HAS_RETURN 0x20 /* Already emitted a return. */ +#define PROTO_FIXUP_RETURN 0x40 /* Need to fixup emitted returns. */ +/* Top bits used for counting created closures. */ +#define PROTO_CLCOUNT 0x20 /* Base of saturating 3 bit counter. */ +#define PROTO_CLC_BITS 3 +#define PROTO_CLC_POLY (3*PROTO_CLCOUNT) /* Polymorphic threshold. */ + +#define PROTO_UV_LOCAL 0x8000 /* Upvalue for local slot. */ +#define PROTO_UV_IMMUTABLE 0x4000 /* Immutable upvalue. */ + +#define proto_kgc(pt, idx) \ + check_exp((uintptr_t)(intptr_t)(idx) >= (uintptr_t)-(intptr_t)(pt)->sizekgc, \ + gcref(mref((pt)->k, GCRef)[(idx)])) +#define proto_knumtv(pt, idx) \ + check_exp((uintptr_t)(idx) < (pt)->sizekn, &mref((pt)->k, TValue)[(idx)]) +#define proto_bc(pt) ((BCIns *)((char *)(pt) + sizeof(GCproto))) +#define proto_bcpos(pt, pc) ((BCPos)((pc) - proto_bc(pt))) +#define proto_uv(pt) (mref((pt)->uv, uint16_t)) + +#define proto_chunkname(pt) (strref((pt)->chunkname)) +#define proto_chunknamestr(pt) (strdata(proto_chunkname((pt)))) +#define proto_lineinfo(pt) (mref((pt)->lineinfo, const void)) +#define proto_uvinfo(pt) (mref((pt)->uvinfo, const uint8_t)) +#define proto_varinfo(pt) (mref((pt)->varinfo, const uint8_t)) + +/* -- Upvalue object ------------------------------------------------------ */ + +typedef struct GCupval { + GCHeader; + uint8_t closed; /* Set if closed (i.e. uv->v == &uv->u.value). */ + uint8_t immutable; /* Immutable value. */ + union { + TValue tv; /* If closed: the value itself. */ + struct { /* If open: double linked list, anchored at thread. */ + GCRef prev; + GCRef next; + }; + }; + MRef v; /* Points to stack slot (open) or above (closed). */ + uint32_t dhash; /* Disambiguation hash: dh1 != dh2 => cannot alias. */ +} GCupval; + +#define uvprev(uv_) (&gcref((uv_)->prev)->uv) +#define uvnext(uv_) (&gcref((uv_)->next)->uv) +#define uvval(uv_) (mref((uv_)->v, TValue)) + +/* -- Function object (closures) ------------------------------------------ */ + +/* Common header for functions. env should be at same offset in GCudata. */ +#define GCfuncHeader \ + GCHeader; uint8_t ffid; uint8_t nupvalues; \ + GCRef env; GCRef gclist; MRef pc + +typedef struct GCfuncC { + GCfuncHeader; + lua_CFunction f; /* C function to be called. */ + TValue upvalue[1]; /* Array of upvalues (TValue). */ +} GCfuncC; + +typedef struct GCfuncL { + GCfuncHeader; + GCRef uvptr[1]; /* Array of _pointers_ to upvalue objects (GCupval). */ +} GCfuncL; + +typedef union GCfunc { + GCfuncC c; + GCfuncL l; +} GCfunc; + +#define FF_LUA 0 +#define FF_C 1 +#define isluafunc(fn) ((fn)->c.ffid == FF_LUA) +#define iscfunc(fn) ((fn)->c.ffid == FF_C) +#define isffunc(fn) ((fn)->c.ffid > FF_C) +#define funcproto(fn) \ + check_exp(isluafunc(fn), (GCproto *)(mref((fn)->l.pc, char)-sizeof(GCproto))) +#define sizeCfunc(n) (sizeof(GCfuncC)-sizeof(TValue)+sizeof(TValue)*(n)) +#define sizeLfunc(n) (sizeof(GCfuncL)-sizeof(GCRef)+sizeof(GCRef)*(n)) + +/* -- Table object -------------------------------------------------------- */ + +/* Hash node. */ +typedef struct Node { + TValue val; /* Value object. Must be first field. */ + TValue key; /* Key object. */ + MRef next; /* Hash chain. */ +#if !LJ_GC64 + MRef freetop; /* Top of free elements (stored in t->node[0]). */ +#endif +} Node; + +LJ_STATIC_ASSERT(offsetof(Node, val) == 0); + +typedef struct GCtab { + GCHeader; + uint8_t nomm; /* Negative cache for fast metamethods. */ + int8_t colo; /* Array colocation. */ + MRef array; /* Array part. */ + GCRef gclist; + GCRef metatable; /* Must be at same offset in GCudata. */ + MRef node; /* Hash part. */ + uint32_t asize; /* Size of array part (keys [0, asize-1]). */ + uint32_t hmask; /* Hash part mask (size of hash part - 1). */ +#if LJ_GC64 + MRef freetop; /* Top of free elements. */ +#endif +} GCtab; + +#define sizetabcolo(n) ((n)*sizeof(TValue) + sizeof(GCtab)) +#define tabref(r) (&gcref((r))->tab) +#define noderef(r) (mref((r), Node)) +#define nextnode(n) (mref((n)->next, Node)) +#if LJ_GC64 +#define getfreetop(t, n) (noderef((t)->freetop)) +#define setfreetop(t, n, v) (setmref((t)->freetop, (v))) +#else +#define getfreetop(t, n) (noderef((n)->freetop)) +#define setfreetop(t, n, v) (setmref((n)->freetop, (v))) +#endif + +/* -- State objects ------------------------------------------------------- */ + +/* VM states. */ +enum { + LJ_VMST_INTERP, /* Interpreter. */ + LJ_VMST_C, /* C function. */ + LJ_VMST_GC, /* Garbage collector. */ + LJ_VMST_EXIT, /* Trace exit handler. */ + LJ_VMST_RECORD, /* Trace recorder. */ + LJ_VMST_OPT, /* Optimizer. */ + LJ_VMST_ASM, /* Assembler. */ + LJ_VMST__MAX +}; + +#define setvmstate(g, st) ((g)->vmstate = ~LJ_VMST_##st) + +/* Metamethods. ORDER MM */ +#ifdef LJ_HASFFI +#define MMDEF_FFI(_) _(new) +#else +#define MMDEF_FFI(_) +#endif + +#if LJ_52 || LJ_HASFFI +#define MMDEF_PAIRS(_) _(pairs) _(ipairs) +#else +#define MMDEF_PAIRS(_) +#define MM_pairs 255 +#define MM_ipairs 255 +#endif + +#define MMDEF(_) \ + _(index) _(newindex) _(gc) _(mode) _(eq) _(len) \ + /* Only the above (fast) metamethods are negative cached (max. 8). */ \ + _(lt) _(le) _(concat) _(call) \ + /* The following must be in ORDER ARITH. */ \ + _(add) _(sub) _(mul) _(div) _(mod) _(pow) _(unm) \ + /* The following are used in the standard libraries. */ \ + _(metatable) _(tostring) MMDEF_FFI(_) MMDEF_PAIRS(_) + +typedef enum { +#define MMENUM(name) MM_##name, +MMDEF(MMENUM) +#undef MMENUM + MM__MAX, + MM____ = MM__MAX, + MM_FAST = MM_len +} MMS; + +/* GC root IDs. */ +typedef enum { + GCROOT_MMNAME, /* Metamethod names. */ + GCROOT_MMNAME_LAST = GCROOT_MMNAME + MM__MAX-1, + GCROOT_BASEMT, /* Metatables for base types. */ + GCROOT_BASEMT_NUM = GCROOT_BASEMT + ~LJ_TNUMX, + GCROOT_IO_INPUT, /* Userdata for default I/O input file. */ + GCROOT_IO_OUTPUT, /* Userdata for default I/O output file. */ + GCROOT_MAX +} GCRootID; + +#define basemt_it(g, it) ((g)->gcroot[GCROOT_BASEMT+~(it)]) +#define basemt_obj(g, o) ((g)->gcroot[GCROOT_BASEMT+itypemap(o)]) +#define mmname_str(g, mm) (strref((g)->gcroot[GCROOT_MMNAME+(mm)])) + +typedef struct GCState { + GCSize total; /* Memory currently allocated. */ + GCSize threshold; /* Memory threshold. */ + uint8_t currentwhite; /* Current white color. */ + uint8_t state; /* GC state. */ + uint8_t nocdatafin; /* No cdata finalizer called. */ + uint8_t unused2; + MSize sweepstr; /* Sweep position in string table. */ + GCRef root; /* List of all collectable objects. */ + MRef sweep; /* Sweep position in root list. */ + GCRef gray; /* List of gray objects. */ + GCRef grayagain; /* List of objects for atomic traversal. */ + GCRef weak; /* List of weak tables (to be cleared). */ + GCRef mmudata; /* List of userdata (to be finalized). */ + GCSize debt; /* Debt (how much GC is behind schedule). */ + GCSize estimate; /* Estimate of memory actually in use. */ + MSize stepmul; /* Incremental GC step granularity. */ + MSize pause; /* Pause between successive GC cycles. */ +} GCState; + +/* Global state, shared by all threads of a Lua universe. */ +typedef struct global_State { + GCRef *strhash; /* String hash table (hash chain anchors). */ + MSize strmask; /* String hash mask (size of hash table - 1). */ + MSize strnum; /* Number of strings in hash table. */ + lua_Alloc allocf; /* Memory allocator. */ + void *allocd; /* Memory allocator data. */ + GCState gc; /* Garbage collector. */ + volatile int32_t vmstate; /* VM state or current JIT code trace number. */ + SBuf tmpbuf; /* Temporary string buffer. */ + GCstr strempty; /* Empty string. */ + uint8_t stremptyz; /* Zero terminator of empty string. */ + uint8_t hookmask; /* Hook mask. */ + uint8_t dispatchmode; /* Dispatch mode. */ + uint8_t vmevmask; /* VM event mask. */ + GCRef mainthref; /* Link to main thread. */ + TValue registrytv; /* Anchor for registry. */ + TValue tmptv, tmptv2; /* Temporary TValues. */ + Node nilnode; /* Fallback 1-element hash part (nil key and value). */ + GCupval uvhead; /* Head of double-linked list of all open upvalues. */ + int32_t hookcount; /* Instruction hook countdown. */ + int32_t hookcstart; /* Start count for instruction hook counter. */ + lua_Hook hookf; /* Hook function. */ + lua_CFunction wrapf; /* Wrapper for C function calls. */ + lua_CFunction panic; /* Called as a last resort for errors. */ + BCIns bc_cfunc_int; /* Bytecode for internal C function calls. */ + BCIns bc_cfunc_ext; /* Bytecode for external C function calls. */ + GCRef cur_L; /* Currently executing lua_State. */ + MRef jit_base; /* Current JIT code L->base or NULL. */ + MRef saved_jit_base; /* saved jit_base for lj_err_throw */ + MRef ctype_state; /* Pointer to C type state. */ + GCRef gcroot[GCROOT_MAX]; /* GC roots. */ +} global_State; + +#define mainthread(g) (&gcref(g->mainthref)->th) +#define niltv(L) \ + check_exp(tvisnil(&G(L)->nilnode.val), &G(L)->nilnode.val) +#define niltvg(g) \ + check_exp(tvisnil(&(g)->nilnode.val), &(g)->nilnode.val) + +/* Hook management. Hook event masks are defined in lua.h. */ +#define HOOK_EVENTMASK 0x0f +#define HOOK_ACTIVE 0x10 +#define HOOK_ACTIVE_SHIFT 4 +#define HOOK_VMEVENT 0x20 +#define HOOK_GC 0x40 +#define HOOK_PROFILE 0x80 +#define hook_active(g) ((g)->hookmask & HOOK_ACTIVE) +#define hook_enter(g) ((g)->hookmask |= HOOK_ACTIVE) +#define hook_entergc(g) ((g)->hookmask |= (HOOK_ACTIVE|HOOK_GC)) +#define hook_vmevent(g) ((g)->hookmask |= (HOOK_ACTIVE|HOOK_VMEVENT)) +#define hook_leave(g) ((g)->hookmask &= ~HOOK_ACTIVE) +#define hook_save(g) ((g)->hookmask & ~HOOK_EVENTMASK) +#define hook_restore(g, h) \ + ((g)->hookmask = ((g)->hookmask & HOOK_EVENTMASK) | (h)) + +/* Per-thread state object. */ +struct lua_State { + GCHeader; + uint8_t dummy_ffid; /* Fake FF_C for curr_funcisL() on dummy frames. */ + uint8_t status; /* Thread status. */ + MRef glref; /* Link to global state. */ + GCRef gclist; /* GC chain. */ + TValue *base; /* Base of currently executing function. */ + TValue *top; /* First free slot in the stack. */ + MRef maxstack; /* Last free slot in the stack. */ + MRef stack; /* Stack base. */ + GCRef openupval; /* List of open upvalues in the stack. */ + GCRef env; /* Thread environment (table of globals). */ + void *cframe; /* End of C stack frame chain. */ + MSize stacksize; /* True stack size (incl. LJ_STACK_EXTRA). */ + void *exdata; /* user extra data pointer. added by OpenResty */ +#if LJ_TARGET_ARM + uint32_t unused1; + uint32_t unused2; +#endif +}; + +#define G(L) (mref(L->glref, global_State)) +#define registry(L) (&G(L)->registrytv) + +/* Macros to access the currently executing (Lua) function. */ +#if LJ_GC64 +#define curr_func(L) (&gcval(L->base-2)->fn) +#elif LJ_FR2 +#define curr_func(L) (&gcref((L->base-2)->gcr)->fn) +#else +#define curr_func(L) (&gcref((L->base-1)->fr.func)->fn) +#endif +#define curr_funcisL(L) (isluafunc(curr_func(L))) +#define curr_proto(L) (funcproto(curr_func(L))) +#define curr_topL(L) (L->base + curr_proto(L)->framesize) +#define curr_top(L) (curr_funcisL(L) ? curr_topL(L) : L->top) + +/* -- GC object definition and conversions -------------------------------- */ + +/* GC header for generic access to common fields of GC objects. */ +typedef struct GChead { + GCHeader; + uint8_t unused1; + uint8_t unused2; + GCRef env; + GCRef gclist; + GCRef metatable; +} GChead; + +/* The env field SHOULD be at the same offset for all GC objects. */ +LJ_STATIC_ASSERT(offsetof(GChead, env) == offsetof(GCfuncL, env)); +LJ_STATIC_ASSERT(offsetof(GChead, env) == offsetof(GCudata, env)); + +/* The metatable field MUST be at the same offset for all GC objects. */ +LJ_STATIC_ASSERT(offsetof(GChead, metatable) == offsetof(GCtab, metatable)); +LJ_STATIC_ASSERT(offsetof(GChead, metatable) == offsetof(GCudata, metatable)); + +/* The gclist field MUST be at the same offset for all GC objects. */ +LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(lua_State, gclist)); +LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCproto, gclist)); +LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCfuncL, gclist)); +LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCtab, gclist)); + +typedef union GCobj { + GChead gch; + GCstr str; + GCupval uv; + lua_State th; + GCproto pt; + GCfunc fn; + GCcdata cd; + GCtab tab; + GCudata ud; +} GCobj; + +/* Macros to convert a GCobj pointer into a specific value. */ +#define gco2str(o) check_exp((o)->gch.gct == ~LJ_TSTR, &(o)->str) +#define gco2uv(o) check_exp((o)->gch.gct == ~LJ_TUPVAL, &(o)->uv) +#define gco2th(o) check_exp((o)->gch.gct == ~LJ_TTHREAD, &(o)->th) +#define gco2pt(o) check_exp((o)->gch.gct == ~LJ_TPROTO, &(o)->pt) +#define gco2func(o) check_exp((o)->gch.gct == ~LJ_TFUNC, &(o)->fn) +#define gco2cd(o) check_exp((o)->gch.gct == ~LJ_TCDATA, &(o)->cd) +#define gco2tab(o) check_exp((o)->gch.gct == ~LJ_TTAB, &(o)->tab) +#define gco2ud(o) check_exp((o)->gch.gct == ~LJ_TUDATA, &(o)->ud) + +/* Macro to convert any collectable object into a GCobj pointer. */ +#define obj2gco(v) ((GCobj *)(v)) + +/* -- TValue getters/setters ---------------------------------------------- */ + +#ifdef LUA_USE_ASSERT +#include "lj_gc.h" +#endif + +/* Macros to test types. */ +#if LJ_GC64 +#define itype(o) ((uint32_t)((o)->it64 >> 47)) +#define tvisnil(o) ((o)->it64 == -1) +#else +#define itype(o) ((o)->it) +#define tvisnil(o) (itype(o) == LJ_TNIL) +#endif +#define tvisfalse(o) (itype(o) == LJ_TFALSE) +#define tvistrue(o) (itype(o) == LJ_TTRUE) +#define tvisbool(o) (tvisfalse(o) || tvistrue(o)) +#if LJ_64 && !LJ_GC64 +#define tvislightud(o) (((int32_t)itype(o) >> 15) == -2) +#else +#define tvislightud(o) (itype(o) == LJ_TLIGHTUD) +#endif +#define tvisstr(o) (itype(o) == LJ_TSTR) +#define tvisfunc(o) (itype(o) == LJ_TFUNC) +#define tvisthread(o) (itype(o) == LJ_TTHREAD) +#define tvisproto(o) (itype(o) == LJ_TPROTO) +#define tviscdata(o) (itype(o) == LJ_TCDATA) +#define tvistab(o) (itype(o) == LJ_TTAB) +#define tvisudata(o) (itype(o) == LJ_TUDATA) +#define tvisnumber(o) (itype(o) <= LJ_TISNUM) +#define tvisint(o) (LJ_DUALNUM && itype(o) == LJ_TISNUM) +#define tvisnum(o) (itype(o) < LJ_TISNUM) + +#define tvistruecond(o) (itype(o) < LJ_TISTRUECOND) +#define tvispri(o) (itype(o) >= LJ_TISPRI) +#define tvistabud(o) (itype(o) <= LJ_TISTABUD) /* && !tvisnum() */ +#define tvisgcv(o) ((itype(o) - LJ_TISGCV) > (LJ_TNUMX - LJ_TISGCV)) + +/* Special macros to test numbers for NaN, +0, -0, +1 and raw equality. */ +#define tvisnan(o) ((o)->n != (o)->n) +#if LJ_64 +#define tviszero(o) (((o)->u64 << 1) == 0) +#else +#define tviszero(o) (((o)->u32.lo | ((o)->u32.hi << 1)) == 0) +#endif +#define tvispzero(o) ((o)->u64 == 0) +#define tvismzero(o) ((o)->u64 == U64x(80000000,00000000)) +#define tvispone(o) ((o)->u64 == U64x(3ff00000,00000000)) +#define rawnumequal(o1, o2) ((o1)->u64 == (o2)->u64) + +/* Macros to convert type ids. */ +#if LJ_64 && !LJ_GC64 +#define itypemap(o) \ + (tvisnumber(o) ? ~LJ_TNUMX : tvislightud(o) ? ~LJ_TLIGHTUD : ~itype(o)) +#else +#define itypemap(o) (tvisnumber(o) ? ~LJ_TNUMX : ~itype(o)) +#endif + +/* Macros to get tagged values. */ +#if LJ_GC64 +#define gcval(o) ((GCobj *)(gcrefu((o)->gcr) & LJ_GCVMASK)) +#else +#define gcval(o) (gcref((o)->gcr)) +#endif +#define boolV(o) check_exp(tvisbool(o), (LJ_TFALSE - itype(o))) +#if LJ_64 +#define lightudV(o) \ + check_exp(tvislightud(o), (void *)((o)->u64 & U64x(00007fff,ffffffff))) +#else +#define lightudV(o) check_exp(tvislightud(o), gcrefp((o)->gcr, void)) +#endif +#define gcV(o) check_exp(tvisgcv(o), gcval(o)) +#define strV(o) check_exp(tvisstr(o), &gcval(o)->str) +#define funcV(o) check_exp(tvisfunc(o), &gcval(o)->fn) +#define threadV(o) check_exp(tvisthread(o), &gcval(o)->th) +#define protoV(o) check_exp(tvisproto(o), &gcval(o)->pt) +#define cdataV(o) check_exp(tviscdata(o), &gcval(o)->cd) +#define tabV(o) check_exp(tvistab(o), &gcval(o)->tab) +#define udataV(o) check_exp(tvisudata(o), &gcval(o)->ud) +#define numV(o) check_exp(tvisnum(o), (o)->n) +#define intV(o) check_exp(tvisint(o), (int32_t)(o)->i) + +/* Macros to set tagged values. */ +#if LJ_GC64 +#define setitype(o, i) ((o)->it = ((i) << 15)) +#define setnilV(o) ((o)->it64 = -1) +#define setpriV(o, x) ((o)->it64 = (int64_t)~((uint64_t)~(x)<<47)) +#define setboolV(o, x) ((o)->it64 = (int64_t)~((uint64_t)((x)+1)<<47)) +#else +#define setitype(o, i) ((o)->it = (i)) +#define setnilV(o) ((o)->it = LJ_TNIL) +#define setboolV(o, x) ((o)->it = LJ_TFALSE-(uint32_t)(x)) +#define setpriV(o, i) (setitype((o), (i))) +#endif + +static LJ_AINLINE void setlightudV(TValue *o, void *p) +{ +#if LJ_GC64 + o->u64 = (uint64_t)p | (((uint64_t)LJ_TLIGHTUD) << 47); +#elif LJ_64 + o->u64 = (uint64_t)p | (((uint64_t)0xffff) << 48); +#else + setgcrefp(o->gcr, p); setitype(o, LJ_TLIGHTUD); +#endif +} + +#if LJ_64 +#define checklightudptr(L, p) \ + (((uint64_t)(p) >> 47) ? (lj_err_msg(L, LJ_ERR_BADLU), NULL) : (p)) +#else +#define checklightudptr(L, p) (p) +#endif + +#if LJ_FR2 +#define contptr(f) ((void *)(f)) +#define setcont(o, f) ((o)->u64 = (uint64_t)(uintptr_t)contptr(f)) +#elif LJ_64 +#define contptr(f) \ + ((void *)(uintptr_t)(uint32_t)((intptr_t)(f) - (intptr_t)lj_vm_asm_begin)) +#define setcont(o, f) \ + ((o)->u64 = (uint64_t)(void *)(f) - (uint64_t)lj_vm_asm_begin) +#else +#define contptr(f) ((void *)(f)) +#define setcont(o, f) setlightudV((o), contptr(f)) +#endif + +#define tvchecklive(L, o) \ + UNUSED(L), lua_assert(!tvisgcv(o) || \ + ((~itype(o) == gcval(o)->gch.gct) && !isdead(G(L), gcval(o)))) + +static LJ_AINLINE void setgcVraw(TValue *o, GCobj *v, uint32_t itype) +{ +#if LJ_GC64 + setgcreft(o->gcr, v, itype); +#else + setgcref(o->gcr, v); setitype(o, itype); +#endif +} + +static LJ_AINLINE void setgcV(lua_State *L, TValue *o, GCobj *v, uint32_t it) +{ + setgcVraw(o, v, it); tvchecklive(L, o); +} + +#define define_setV(name, type, tag) \ +static LJ_AINLINE void name(lua_State *L, TValue *o, type *v) \ +{ \ + setgcV(L, o, obj2gco(v), tag); \ +} +define_setV(setstrV, GCstr, LJ_TSTR) +define_setV(setthreadV, lua_State, LJ_TTHREAD) +define_setV(setprotoV, GCproto, LJ_TPROTO) +define_setV(setfuncV, GCfunc, LJ_TFUNC) +define_setV(setcdataV, GCcdata, LJ_TCDATA) +define_setV(settabV, GCtab, LJ_TTAB) +define_setV(setudataV, GCudata, LJ_TUDATA) + +#define setnumV(o, x) ((o)->n = (x)) +#define setnanV(o) ((o)->u64 = U64x(fff80000,00000000)) +#define setpinfV(o) ((o)->u64 = U64x(7ff00000,00000000)) +#define setminfV(o) ((o)->u64 = U64x(fff00000,00000000)) + +static LJ_AINLINE void setintV(TValue *o, int32_t i) +{ +#if LJ_DUALNUM + o->i = (uint32_t)i; setitype(o, LJ_TISNUM); +#else + o->n = (lua_Number)i; +#endif +} + +static LJ_AINLINE void setint64V(TValue *o, int64_t i) +{ + if (LJ_DUALNUM && LJ_LIKELY(i == (int64_t)(int32_t)i)) + setintV(o, (int32_t)i); + else + setnumV(o, (lua_Number)i); +} + +#if LJ_64 +#define setintptrV(o, i) setint64V((o), (i)) +#else +#define setintptrV(o, i) setintV((o), (i)) +#endif + +/* Copy tagged values. */ +static LJ_AINLINE void copyTV(lua_State *L, TValue *o1, const TValue *o2) +{ + *o1 = *o2; tvchecklive(L, o1); +} + +/* -- Number to integer conversion ---------------------------------------- */ + +#if LJ_SOFTFP +LJ_ASMF int32_t lj_vm_tobit(double x); +#if LJ_TARGET_MIPS64 +LJ_ASMF int32_t lj_vm_tointg(double x); +#endif +#endif + +static LJ_AINLINE int32_t lj_num2bit(lua_Number n) +{ +#if LJ_SOFTFP + return lj_vm_tobit(n); +#else + TValue o; + o.n = n + 6755399441055744.0; /* 2^52 + 2^51 */ + return (int32_t)o.u32.lo; +#endif +} + +#define lj_num2int(n) ((int32_t)(n)) + +/* +** This must match the JIT backend behavior. In particular for archs +** that don't have a common hardware instruction for this conversion. +** Note that signed FP to unsigned int conversions have an undefined +** result and should never be relied upon in portable FFI code. +** See also: C99 or C11 standard, 6.3.1.4, footnote of (1). +*/ +static LJ_AINLINE uint64_t lj_num2u64(lua_Number n) +{ +#if LJ_TARGET_X86ORX64 || LJ_TARGET_MIPS + int64_t i = (int64_t)n; + if (i < 0) i = (int64_t)(n - 18446744073709551616.0); + return (uint64_t)i; +#else + return (uint64_t)n; +#endif +} + +static LJ_AINLINE int32_t numberVint(cTValue *o) +{ + if (LJ_LIKELY(tvisint(o))) + return intV(o); + else + return lj_num2int(numV(o)); +} + +static LJ_AINLINE lua_Number numberVnum(cTValue *o) +{ + if (LJ_UNLIKELY(tvisint(o))) + return (lua_Number)intV(o); + else + return numV(o); +} + +/* -- Miscellaneous object handling --------------------------------------- */ + +/* Names and maps for internal and external object tags. */ +LJ_DATA const char *const lj_obj_typename[1+LUA_TCDATA+1]; +LJ_DATA const char *const lj_obj_itypename[~LJ_TNUMX+1]; + +#define lj_typename(o) (lj_obj_itypename[itypemap(o)]) + +/* Compare two objects without calling metamethods. */ +LJ_FUNC int LJ_FASTCALL lj_obj_equal(cTValue *o1, cTValue *o2); +LJ_FUNC const void * LJ_FASTCALL lj_obj_ptr(cTValue *o); + +#endif diff --git a/lua/lua51/lua.h b/lua/lua/lua.h similarity index 91% rename from lua/lua51/lua.h rename to lua/lua/lua.h index e4bdfd3..aa0d2ee 100644 --- a/lua/lua51/lua.h +++ b/lua/lua/lua.h @@ -11,6 +11,7 @@ #include #include +#include #include "luaconf.h" @@ -20,7 +21,7 @@ #define LUA_RELEASE "Lua 5.1.4" #define LUA_VERSION_NUM 501 #define LUA_COPYRIGHT "Copyright (C) 1994-2008 Lua.org, PUC-Rio" -#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" +#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" /* mark for precompiled code (`Lua') */ @@ -39,7 +40,8 @@ #define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) -/* thread status; 0 is OK */ +/* thread status */ +#define LUA_OK 0 #define LUA_YIELD 1 #define LUA_ERRRUN 2 #define LUA_ERRSYNTAX 3 @@ -144,6 +146,9 @@ LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2); LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx); +LUA_API int64_t (lua_cdata_to_int64) (lua_State *L, int idx); +LUA_API int32_t (lua_cdata_to_int32) (lua_State *L, int idx); +LUA_API uint64_t (lua_cdata_to_uint64) (lua_State *L, int idx); LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx); LUA_API int (lua_toboolean) (lua_State *L, int idx); LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); @@ -226,6 +231,7 @@ LUA_API int (lua_status) (lua_State *L); #define LUA_GCSTEP 5 #define LUA_GCSETPAUSE 6 #define LUA_GCSETSTEPMUL 7 +#define LUA_GCISRUNNING 9 LUA_API int (lua_gc) (lua_State *L, int what, int data); @@ -243,9 +249,11 @@ LUA_API void (lua_concat) (lua_State *L, int n); LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); +LUA_API void lua_setexdata(lua_State *L, void *exdata); +LUA_API void *lua_getexdata(lua_State *L); -/* +/* ** =============================================================== ** some useful macros ** =============================================================== @@ -336,12 +344,24 @@ LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n); LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n); - LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count); LUA_API lua_Hook lua_gethook (lua_State *L); LUA_API int lua_gethookmask (lua_State *L); LUA_API int lua_gethookcount (lua_State *L); +/* From Lua 5.2. */ +LUA_API void *lua_upvalueid (lua_State *L, int idx, int n); +LUA_API void lua_upvaluejoin (lua_State *L, int idx1, int n1, int idx2, int n2); +LUA_API int lua_loadx (lua_State *L, lua_Reader reader, void *dt, + const char *chunkname, const char *mode); +LUA_API const lua_Number *lua_version (lua_State *L); +LUA_API void lua_copy (lua_State *L, int fromidx, int toidx); +LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *isnum); +LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *isnum); + +/* From Lua 5.3. */ +LUA_API int lua_isyieldable (lua_State *L); + struct lua_Debug { int event; diff --git a/lua/lua/luaconf.h b/lua/lua/luaconf.h new file mode 100644 index 0000000..28a839e --- /dev/null +++ b/lua/lua/luaconf.h @@ -0,0 +1,160 @@ +/* +** Configuration header. +** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h +*/ + +#ifndef luaconf_h +#define luaconf_h + +#ifndef WINVER +#define WINVER 0x0501 +#endif +#include +#include + +/* Default path for loading Lua and C modules with require(). */ +#if defined(_WIN32) || defined(_WIN64) +/* +** In Windows, any exclamation mark ('!') in the path is replaced by the +** path of the directory of the executable file of the current process. +*/ +#define LUA_LDIR "!\\lua\\" +#define LUA_CDIR "!\\" +#ifndef LUA_PATH_DEFAULT +#define LUA_PATH_DEFAULT \ + ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" +#endif +#ifndef LUA_CPATH_DEFAULT +#define LUA_CPATH_DEFAULT \ + ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" +#endif +#else +/* +** Note to distribution maintainers: do NOT patch the following lines! +** Please read ../doc/install.html#distro and pass PREFIX=/usr instead. +*/ +#ifndef LUA_MULTILIB +#define LUA_MULTILIB "lib" +#endif +#ifndef LUA_LMULTILIB +#define LUA_LMULTILIB "lib" +#endif +#define LUA_LROOT "/usr/local" +#define LUA_LUADIR "/lua/5.1/" +#define LUA_LJDIR "/luajit-2.1.0-beta3/" + +#ifdef LUA_ROOT +#define LUA_JROOT LUA_ROOT +#define LUA_RLDIR LUA_ROOT "/share" LUA_LUADIR +#define LUA_RCDIR LUA_ROOT "/" LUA_MULTILIB LUA_LUADIR +#define LUA_RLPATH ";" LUA_RLDIR "?.lua;" LUA_RLDIR "?/init.lua" +#define LUA_RCPATH ";" LUA_RCDIR "?.so" +#else +#define LUA_JROOT LUA_LROOT +#define LUA_RLPATH +#define LUA_RCPATH +#endif + +#define LUA_JPATH ";" LUA_JROOT "/share" LUA_LJDIR "?.lua" +#define LUA_LLDIR LUA_LROOT "/share" LUA_LUADIR +#define LUA_LCDIR LUA_LROOT "/" LUA_LMULTILIB LUA_LUADIR +#define LUA_LLPATH ";" LUA_LLDIR "?.lua;" LUA_LLDIR "?/init.lua" +#define LUA_LCPATH1 ";" LUA_LCDIR "?.so" +#define LUA_LCPATH2 ";" LUA_LCDIR "loadall.so" + +#ifndef LUA_PATH_DEFAULT +#define LUA_PATH_DEFAULT "./?.lua" LUA_JPATH LUA_LLPATH LUA_RLPATH +#endif +#ifndef LUA_CPATH_DEFAULT +#define LUA_CPATH_DEFAULT "./?.so" LUA_LCPATH1 LUA_RCPATH LUA_LCPATH2 +#endif +#endif + +/* Environment variable names for path overrides and initialization code. */ +#define LUA_PATH "LUA_PATH" +#define LUA_CPATH "LUA_CPATH" +#define LUA_INIT "LUA_INIT" + +/* Special file system characters. */ +#if defined(_WIN32) || defined(_WIN64) +#define LUA_DIRSEP "\\" +#else +#define LUA_DIRSEP "/" +#endif +#define LUA_PATHSEP ";" +#define LUA_PATH_MARK "?" +#define LUA_EXECDIR "!" +#define LUA_IGMARK "-" +#define LUA_PATH_CONFIG \ + LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n" \ + LUA_EXECDIR "\n" LUA_IGMARK "\n" + +/* Quoting in error messages. */ +#define LUA_QL(x) "'" x "'" +#define LUA_QS LUA_QL("%s") + +/* Various tunables. */ +#define LUAI_MAXSTACK 65500 /* Max. # of stack slots for a thread (<64K). */ +#define LUAI_MAXCSTACK 8000 /* Max. # of stack slots for a C func (<10K). */ +#define LUAI_GCPAUSE 200 /* Pause GC until memory is at 200%. */ +#define LUAI_GCMUL 200 /* Run GC at 200% of allocation speed. */ +#define LUA_MAXCAPTURES 32 /* Max. pattern captures. */ + +/* Configuration for the frontend (the luajit executable). */ +#if defined(luajit_c) +#define LUA_PROGNAME "luajit" /* Fallback frontend name. */ +#define LUA_PROMPT "> " /* Interactive prompt. */ +#define LUA_PROMPT2 ">> " /* Continuation prompt. */ +#define LUA_MAXINPUT 512 /* Max. input line length. */ +#endif + +/* Note: changing the following defines breaks the Lua 5.1 ABI. */ +#define LUA_INTEGER ptrdiff_t +#define LUA_IDSIZE 60 /* Size of lua_Debug.short_src. */ +/* +** Size of lauxlib and io.* on-stack buffers. Weird workaround to avoid using +** unreasonable amounts of stack space, but still retain ABI compatibility. +** Blame Lua for depending on BUFSIZ in the ABI, blame **** for wrecking it. +*/ +#define LUAL_BUFFERSIZE (BUFSIZ > 16384 ? 8192 : BUFSIZ) + +/* The following defines are here only for compatibility with luaconf.h +** from the standard Lua distribution. They must not be changed for LuaJIT. +*/ +#define LUA_NUMBER_DOUBLE +#define LUA_NUMBER double +#define LUAI_UACNUMBER double +#define LUA_NUMBER_SCAN "%lf" +#define LUA_NUMBER_FMT "%.14g" +#define lua_number2str(s, n) sprintf((s), LUA_NUMBER_FMT, (n)) +#define LUAI_MAXNUMBER2STR 32 +#define LUA_INTFRMLEN "l" +#define LUA_INTFRM_T long + +/* Linkage of public API functions. */ +#if defined(LUA_BUILD_AS_DLL) +#if defined(LUA_CORE) || defined(LUA_LIB) +#define LUA_API __declspec(dllexport) +#else +#define LUA_API __declspec(dllimport) +#endif +#else +#define LUA_API extern +#endif + +#define LUALIB_API LUA_API + +/* Support for internal assertions. */ +#if defined(LUA_USE_ASSERT) || defined(LUA_USE_APICHECK) +#include +#endif +#ifdef LUA_USE_ASSERT +#define lua_assert(x) assert(x) +#endif +#ifdef LUA_USE_APICHECK +#define luai_apicheck(L, o) { (void)L; assert(o); } +#else +#define luai_apicheck(L, o) { (void)L; } +#endif + +#endif diff --git a/lua/lua/luajit-ffi-ctypeid.h b/lua/lua/luajit-ffi-ctypeid.h new file mode 100644 index 0000000..efe5dca --- /dev/null +++ b/lua/lua/luajit-ffi-ctypeid.h @@ -0,0 +1,14 @@ +#ifndef _LUAJIT_FFI_CTYPEID_H +#define _LUAJIT_FFI_CTYPEID_H + +#if LJ_HASFFI +#include "lj_obj.h" + +/* return the ctype of the cdata at the top of the stack*/ +LUA_API uint32_t luajit_ctypeid(struct lua_State *L, int idx); + +LUA_API void luajit_push_cdata_int64(struct lua_State *L, int64_t n); +LUA_API void luajit_push_cdata_uint64(struct lua_State *L, int64_t n); + +#endif +#endif diff --git a/lua/lua/lualib.h b/lua/lua/lualib.h new file mode 100644 index 0000000..6aceabe --- /dev/null +++ b/lua/lua/lualib.h @@ -0,0 +1,44 @@ +/* +** Standard library header. +** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h +*/ + +#ifndef _LUALIB_H +#define _LUALIB_H + +#include "lua.h" + +#define LUA_FILEHANDLE "FILE*" + +#define LUA_COLIBNAME "coroutine" +#define LUA_MATHLIBNAME "math" +#define LUA_STRLIBNAME "string" +#define LUA_TABLIBNAME "table" +#define LUA_IOLIBNAME "io" +#define LUA_OSLIBNAME "os" +#define LUA_LOADLIBNAME "package" +#define LUA_DBLIBNAME "debug" +#define LUA_BITLIBNAME "bit" +#define LUA_JITLIBNAME "jit" +#define LUA_FFILIBNAME "ffi" +#define LUA_THRLIBNAME "thread" + +LUALIB_API int luaopen_base(lua_State *L); +LUALIB_API int luaopen_math(lua_State *L); +LUALIB_API int luaopen_string(lua_State *L); +LUALIB_API int luaopen_table(lua_State *L); +LUALIB_API int luaopen_io(lua_State *L); +LUALIB_API int luaopen_os(lua_State *L); +LUALIB_API int luaopen_package(lua_State *L); +LUALIB_API int luaopen_debug(lua_State *L); +LUALIB_API int luaopen_bit(lua_State *L); +LUALIB_API int luaopen_jit(lua_State *L); +LUALIB_API int luaopen_ffi(lua_State *L); + +LUALIB_API void luaL_openlibs(lua_State *L); + +#ifndef lua_assert +#define lua_assert(x) ((void)0) +#endif + +#endif diff --git a/lua/lua51/luaconf.h b/lua/lua51/luaconf.h deleted file mode 100644 index 3a099ce..0000000 --- a/lua/lua51/luaconf.h +++ /dev/null @@ -1,767 +0,0 @@ -/* -** $Id: luaconf.h,v 1.82.1.7 2008/02/11 16:25:08 roberto Exp $ -** Configuration file for Lua -** See Copyright Notice in lua.h -*/ - - -#ifndef lconfig_h -#define lconfig_h - -#include -#include - - -/* -** ================================================================== -** Search for "@@" to find all configurable definitions. -** =================================================================== -*/ - - -/* -@@ LUA_ANSI controls the use of non-ansi features. -** CHANGE it (define it) if you want Lua to avoid the use of any -** non-ansi feature or library. -*/ -#if defined(__STRICT_ANSI__) -#define LUA_ANSI -#endif - - -#if !defined(LUA_ANSI) && defined(_WIN32) -#define LUA_WIN -#endif - -#if defined(LUA_USE_LINUX) -#define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ -#define LUA_USE_READLINE /* needs some extra libraries */ -#endif - -#if defined(LUA_USE_MACOSX) -#define LUA_USE_POSIX -#define LUA_DL_DYLD /* does not need extra library */ -#endif - - - -/* -@@ LUA_USE_POSIX includes all functionallity listed as X/Open System -@* Interfaces Extension (XSI). -** CHANGE it (define it) if your system is XSI compatible. -*/ -#if defined(LUA_USE_POSIX) -#define LUA_USE_MKSTEMP -#define LUA_USE_ISATTY -#define LUA_USE_POPEN -#define LUA_USE_ULONGJMP -#endif - - -/* -@@ LUA_PATH and LUA_CPATH are the names of the environment variables that -@* Lua check to set its paths. -@@ LUA_INIT is the name of the environment variable that Lua -@* checks for initialization code. -** CHANGE them if you want different names. -*/ -#define LUA_PATH "LUA_PATH" -#define LUA_CPATH "LUA_CPATH" -#define LUA_INIT "LUA_INIT" - - -/* -@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for -@* Lua libraries. -@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for -@* C libraries. -** CHANGE them if your machine has a non-conventional directory -** hierarchy or if you want to install your libraries in -** non-conventional directories. -*/ -#if defined(_WIN32) -/* -** In Windows, any exclamation mark ('!') in the path is replaced by the -** path of the directory of the executable file of the current process. -*/ -#define LUA_LDIR "!\\lua\\" -#define LUA_CDIR "!\\" -#define LUA_PATH_DEFAULT \ - ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua" -#define LUA_CPATH_DEFAULT \ - ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" - -#else -#define LUA_ROOT "/usr/local/" -#define LUA_ROOT2 "/usr/" -#define LUA_LDIR LUA_ROOT "share/lua/5.1/" -#define LUA_LDIR2 LUA_ROOT2 "share/lua/5.1/" -#define LUA_CDIR LUA_ROOT "lib/lua/5.1/" -#define LUA_CDIR2 LUA_ROOT2 "lib/lua/5.1/" -#define LUA_PATH_DEFAULT \ - "./?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \ - LUA_LDIR2"?.lua;" LUA_LDIR2"?/init.lua" -#define LUA_CPATH_DEFAULT \ - "./?.so;" LUA_CDIR"?.so;" LUA_CDIR2"?.so;" LUA_CDIR"loadall.so" -#endif - - -/* -@@ LUA_DIRSEP is the directory separator (for submodules). -** CHANGE it if your machine does not use "/" as the directory separator -** and is not Windows. (On Windows Lua automatically uses "\".) -*/ -#if defined(_WIN32) -#define LUA_DIRSEP "\\" -#else -#define LUA_DIRSEP "/" -#endif - - -/* -@@ LUA_PATHSEP is the character that separates templates in a path. -@@ LUA_PATH_MARK is the string that marks the substitution points in a -@* template. -@@ LUA_EXECDIR in a Windows path is replaced by the executable's -@* directory. -@@ LUA_IGMARK is a mark to ignore all before it when bulding the -@* luaopen_ function name. -** CHANGE them if for some reason your system cannot use those -** characters. (E.g., if one of those characters is a common character -** in file/directory names.) Probably you do not need to change them. -*/ -#define LUA_PATHSEP ";" -#define LUA_PATH_MARK "?" -#define LUA_EXECDIR "!" -#define LUA_IGMARK "-" - - -/* -@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger. -** CHANGE that if ptrdiff_t is not adequate on your machine. (On most -** machines, ptrdiff_t gives a good choice between int or long.) -*/ -#define LUA_INTEGER ptrdiff_t - - -/* -@@ LUA_API is a mark for all core API functions. -@@ LUALIB_API is a mark for all standard library functions. -** CHANGE them if you need to define those functions in some special way. -** For instance, if you want to create one Windows DLL with the core and -** the libraries, you may want to use the following definition (define -** LUA_BUILD_AS_DLL to get it). -*/ -#if defined(LUA_BUILD_AS_DLL) - -#if defined(LUA_CORE) || defined(LUA_LIB) -#define LUA_API __declspec(dllexport) -#else -#define LUA_API __declspec(dllimport) -#endif - -#else - -#define LUA_API extern - -#endif - -/* more often than not the libs go together with the core */ -#define LUALIB_API LUA_API - - -/* -@@ LUAI_FUNC is a mark for all extern functions that are not to be -@* exported to outside modules. -@@ LUAI_DATA is a mark for all extern (const) variables that are not to -@* be exported to outside modules. -** CHANGE them if you need to mark them in some special way. Elf/gcc -** (versions 3.2 and later) mark them as "hidden" to optimize access -** when Lua is compiled as a shared library. -*/ -#if defined(luaall_c) -#define LUAI_FUNC static -#define LUAI_DATA /* empty */ - -#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ - defined(__ELF__) -#define LUAI_FUNC __attribute__((visibility("hidden"))) extern -#define LUAI_DATA LUAI_FUNC - -#else -#define LUAI_FUNC extern -#define LUAI_DATA extern -#endif - - - -/* -@@ LUA_QL describes how error messages quote program elements. -** CHANGE it if you want a different appearance. -*/ -#define LUA_QL(x) "'" x "'" -#define LUA_QS LUA_QL("%s") - - -/* -@@ LUA_IDSIZE gives the maximum size for the description of the source -@* of a function in debug information. -** CHANGE it if you want a different size. -*/ -#define LUA_IDSIZE 60 - - -/* -** {================================================================== -** Stand-alone configuration -** =================================================================== -*/ - -#if defined(lua_c) || defined(luaall_c) - -/* -@@ lua_stdin_is_tty detects whether the standard input is a 'tty' (that -@* is, whether we're running lua interactively). -** CHANGE it if you have a better definition for non-POSIX/non-Windows -** systems. -*/ -#if defined(LUA_USE_ISATTY) -#include -#define lua_stdin_is_tty() isatty(0) -#elif defined(LUA_WIN) -#include -#include -#define lua_stdin_is_tty() _isatty(_fileno(stdin)) -#else -#define lua_stdin_is_tty() 1 /* assume stdin is a tty */ -#endif - - -/* -@@ LUA_PROMPT is the default prompt used by stand-alone Lua. -@@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua. -** CHANGE them if you want different prompts. (You can also change the -** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.) -*/ -#define LUA_PROMPT "> " -#define LUA_PROMPT2 ">> " - - -/* -@@ LUA_PROGNAME is the default name for the stand-alone Lua program. -** CHANGE it if your stand-alone interpreter has a different name and -** your system is not able to detect that name automatically. -*/ -#define LUA_PROGNAME "lua" - - -/* -@@ LUA_MAXINPUT is the maximum length for an input line in the -@* stand-alone interpreter. -** CHANGE it if you need longer lines. -*/ -#define LUA_MAXINPUT 512 - - -/* -@@ lua_readline defines how to show a prompt and then read a line from -@* the standard input. -@@ lua_saveline defines how to "save" a read line in a "history". -@@ lua_freeline defines how to free a line read by lua_readline. -** CHANGE them if you want to improve this functionality (e.g., by using -** GNU readline and history facilities). -*/ -#if defined(LUA_USE_READLINE) -#include -#include -#include -#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) -#define lua_saveline(L,idx) \ - if (lua_strlen(L,idx) > 0) /* non-empty line? */ \ - add_history(lua_tostring(L, idx)); /* add it to history */ -#define lua_freeline(L,b) ((void)L, free(b)) -#else -#define lua_readline(L,b,p) \ - ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ - fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ -#define lua_saveline(L,idx) { (void)L; (void)idx; } -#define lua_freeline(L,b) { (void)L; (void)b; } -#endif - -#endif - -/* }================================================================== */ - - -/* -@@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles -@* as a percentage. -** CHANGE it if you want the GC to run faster or slower (higher values -** mean larger pauses which mean slower collection.) You can also change -** this value dynamically. -*/ -#define LUAI_GCPAUSE 200 /* 200% (wait memory to double before next GC) */ - - -/* -@@ LUAI_GCMUL defines the default speed of garbage collection relative to -@* memory allocation as a percentage. -** CHANGE it if you want to change the granularity of the garbage -** collection. (Higher values mean coarser collections. 0 represents -** infinity, where each step performs a full collection.) You can also -** change this value dynamically. -*/ -#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */ - - - -/* -@@ LUA_COMPAT_GETN controls compatibility with old getn behavior. -** CHANGE it (define it) if you want exact compatibility with the -** behavior of setn/getn in Lua 5.0. -*/ -#undef LUA_COMPAT_GETN - -/* -@@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib. -** CHANGE it to undefined as soon as you do not need a global 'loadlib' -** function (the function is still available as 'package.loadlib'). -*/ -#undef LUA_COMPAT_LOADLIB - -/* -@@ LUA_COMPAT_VARARG controls compatibility with old vararg feature. -** CHANGE it to undefined as soon as your programs use only '...' to -** access vararg parameters (instead of the old 'arg' table). -*/ -#define LUA_COMPAT_VARARG - -/* -@@ LUA_COMPAT_MOD controls compatibility with old math.mod function. -** CHANGE it to undefined as soon as your programs use 'math.fmod' or -** the new '%' operator instead of 'math.mod'. -*/ -#define LUA_COMPAT_MOD - -/* -@@ LUA_COMPAT_LSTR controls compatibility with old long string nesting -@* facility. -** CHANGE it to 2 if you want the old behaviour, or undefine it to turn -** off the advisory error when nesting [[...]]. -*/ -#define LUA_COMPAT_LSTR 1 - -/* -@@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name. -** CHANGE it to undefined as soon as you rename 'string.gfind' to -** 'string.gmatch'. -*/ -#define LUA_COMPAT_GFIND - -/* -@@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib' -@* behavior. -** CHANGE it to undefined as soon as you replace to 'luaL_register' -** your uses of 'luaL_openlib' -*/ -#define LUA_COMPAT_OPENLIB - - - -/* -@@ luai_apicheck is the assert macro used by the Lua-C API. -** CHANGE luai_apicheck if you want Lua to perform some checks in the -** parameters it gets from API calls. This may slow down the interpreter -** a bit, but may be quite useful when debugging C code that interfaces -** with Lua. A useful redefinition is to use assert.h. -*/ -#if defined(LUA_USE_APICHECK) -#include -#define luai_apicheck(L,o) { (void)L; assert(o); } -#else -#define luai_apicheck(L,o) { (void)L; } -#endif - - -/* -@@ LUAI_BITSINT defines the number of bits in an int. -** CHANGE here if Lua cannot automatically detect the number of bits of -** your machine. Probably you do not need to change this. -*/ -/* avoid overflows in comparison */ -#if INT_MAX-20 < 32760 -#define LUAI_BITSINT 16 -#elif INT_MAX > 2147483640L -/* int has at least 32 bits */ -#define LUAI_BITSINT 32 -#else -#error "you must define LUA_BITSINT with number of bits in an integer" -#endif - - -/* -@@ LUAI_UINT32 is an unsigned integer with at least 32 bits. -@@ LUAI_INT32 is an signed integer with at least 32 bits. -@@ LUAI_UMEM is an unsigned integer big enough to count the total -@* memory used by Lua. -@@ LUAI_MEM is a signed integer big enough to count the total memory -@* used by Lua. -** CHANGE here if for some weird reason the default definitions are not -** good enough for your machine. (The definitions in the 'else' -** part always works, but may waste space on machines with 64-bit -** longs.) Probably you do not need to change this. -*/ -#if LUAI_BITSINT >= 32 -#define LUAI_UINT32 unsigned int -#define LUAI_INT32 int -#define LUAI_MAXINT32 INT_MAX -#define LUAI_UMEM size_t -#define LUAI_MEM ptrdiff_t -#else -/* 16-bit ints */ -#define LUAI_UINT32 unsigned long -#define LUAI_INT32 long -#define LUAI_MAXINT32 LONG_MAX -#define LUAI_UMEM unsigned long -#define LUAI_MEM long -#endif - - -/* -@@ LUAI_MAXCALLS limits the number of nested calls. -** CHANGE it if you need really deep recursive calls. This limit is -** arbitrary; its only purpose is to stop infinite recursion before -** exhausting memory. -*/ -#define LUAI_MAXCALLS 20000 - - -/* -@@ LUAI_MAXCSTACK limits the number of Lua stack slots that a C function -@* can use. -** CHANGE it if you need lots of (Lua) stack space for your C -** functions. This limit is arbitrary; its only purpose is to stop C -** functions to consume unlimited stack space. (must be smaller than -** -LUA_REGISTRYINDEX) -*/ -#define LUAI_MAXCSTACK 8000 - - - -/* -** {================================================================== -** CHANGE (to smaller values) the following definitions if your system -** has a small C stack. (Or you may want to change them to larger -** values if your system has a large C stack and these limits are -** too rigid for you.) Some of these constants control the size of -** stack-allocated arrays used by the compiler or the interpreter, while -** others limit the maximum number of recursive calls that the compiler -** or the interpreter can perform. Values too large may cause a C stack -** overflow for some forms of deep constructs. -** =================================================================== -*/ - - -/* -@@ LUAI_MAXCCALLS is the maximum depth for nested C calls (short) and -@* syntactical nested non-terminals in a program. -*/ -#define LUAI_MAXCCALLS 200 - - -/* -@@ LUAI_MAXVARS is the maximum number of local variables per function -@* (must be smaller than 250). -*/ -#define LUAI_MAXVARS 200 - - -/* -@@ LUAI_MAXUPVALUES is the maximum number of upvalues per function -@* (must be smaller than 250). -*/ -#define LUAI_MAXUPVALUES 60 - - -/* -@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. -*/ -#define LUAL_BUFFERSIZE BUFSIZ - -/* }================================================================== */ - - - - -/* -** {================================================================== -@@ LUA_NUMBER is the type of numbers in Lua. -** CHANGE the following definitions only if you want to build Lua -** with a number type different from double. You may also need to -** change lua_number2int & lua_number2integer. -** =================================================================== -*/ - -#define LUA_NUMBER_DOUBLE -#define LUA_NUMBER double - -/* -@@ LUAI_UACNUMBER is the result of an 'usual argument conversion' -@* over a number. -*/ -#define LUAI_UACNUMBER double - - -/* -@@ LUA_NUMBER_SCAN is the format for reading numbers. -@@ LUA_NUMBER_FMT is the format for writing numbers. -@@ lua_number2str converts a number to a string. -@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion. -@@ lua_str2number converts a string to a number. -*/ -#define LUA_NUMBER_SCAN "%lf" -#define LUA_NUMBER_FMT "%.14g" -#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) -#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */ -#define lua_str2number(s,p) strtod((s), (p)) - - -/* -@@ The luai_num* macros define the primitive operations over numbers. -*/ -#if defined(LUA_CORE) -#include -#define luai_numadd(a,b) ((a)+(b)) -#define luai_numsub(a,b) ((a)-(b)) -#define luai_nummul(a,b) ((a)*(b)) -#define luai_numdiv(a,b) ((a)/(b)) -#define luai_nummod(a,b) ((a) - floor((a)/(b))*(b)) -#define luai_numpow(a,b) (pow(a,b)) -#define luai_numunm(a) (-(a)) -#define luai_numeq(a,b) ((a)==(b)) -#define luai_numlt(a,b) ((a)<(b)) -#define luai_numle(a,b) ((a)<=(b)) -#define luai_numisnan(a) (!luai_numeq((a), (a))) -#endif - - -/* -@@ lua_number2int is a macro to convert lua_Number to int. -@@ lua_number2integer is a macro to convert lua_Number to lua_Integer. -** CHANGE them if you know a faster way to convert a lua_Number to -** int (with any rounding method and without throwing errors) in your -** system. In Pentium machines, a naive typecast from double to int -** in C is extremely slow, so any alternative is worth trying. -*/ - -/* On a Pentium, resort to a trick */ -#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \ - (defined(__i386) || defined (_M_IX86) || defined(__i386__)) - -/* On a Microsoft compiler, use assembler */ -#if defined(_MSC_VER) - -#define lua_number2int(i,d) __asm fld d __asm fistp i -#define lua_number2integer(i,n) lua_number2int(i, n) - -/* the next trick should work on any Pentium, but sometimes clashes - with a DirectX idiosyncrasy */ -#else - -union luai_Cast { double l_d; long l_l; }; -#define lua_number2int(i,d) \ - { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; } -#define lua_number2integer(i,n) lua_number2int(i, n) - -#endif - - -/* this option always works, but may be slow */ -#else -#define lua_number2int(i,d) ((i)=(int)(d)) -#define lua_number2integer(i,d) ((i)=(lua_Integer)(d)) - -#endif - -/* }================================================================== */ - - -/* -@@ LUAI_USER_ALIGNMENT_T is a type that requires maximum alignment. -** CHANGE it if your system requires alignments larger than double. (For -** instance, if your system supports long doubles and they must be -** aligned in 16-byte boundaries, then you should add long double in the -** union.) Probably you do not need to change this. -*/ -#define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; } - - -/* -@@ LUAI_THROW/LUAI_TRY define how Lua does exception handling. -** CHANGE them if you prefer to use longjmp/setjmp even with C++ -** or if want/don't to use _longjmp/_setjmp instead of regular -** longjmp/setjmp. By default, Lua handles errors with exceptions when -** compiling as C++ code, with _longjmp/_setjmp when asked to use them, -** and with longjmp/setjmp otherwise. -*/ -#if defined(__cplusplus) -/* C++ exceptions */ -#define LUAI_THROW(L,c) throw(c) -#define LUAI_TRY(L,c,a) try { a } catch(...) \ - { if ((c)->status == 0) (c)->status = -1; } -#define luai_jmpbuf int /* dummy variable */ - -#elif defined(LUA_USE_ULONGJMP) -/* in Unix, try _longjmp/_setjmp (more efficient) */ -#define LUAI_THROW(L,c) _longjmp((c)->b, 1) -#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } -#define luai_jmpbuf jmp_buf - -#else -/* default handling with long jumps */ -#define LUAI_THROW(L,c) longjmp((c)->b, 1) -#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } -#define luai_jmpbuf jmp_buf - -#endif - - -/* -@@ LUA_MAXCAPTURES is the maximum number of captures that a pattern -@* can do during pattern-matching. -** CHANGE it if you need more captures. This limit is arbitrary. -*/ -#define LUA_MAXCAPTURES 32 - - -/* -@@ lua_tmpnam is the function that the OS library uses to create a -@* temporary name. -@@ LUA_TMPNAMBUFSIZE is the maximum size of a name created by lua_tmpnam. -** CHANGE them if you have an alternative to tmpnam (which is considered -** insecure) or if you want the original tmpnam anyway. By default, Lua -** uses tmpnam except when POSIX is available, where it uses mkstemp. -*/ -#if defined(loslib_c) || defined(luaall_c) - -#if defined(LUA_USE_MKSTEMP) -#include -#define LUA_TMPNAMBUFSIZE 32 -#define lua_tmpnam(b,e) { \ - strcpy(b, "/tmp/lua_XXXXXX"); \ - e = mkstemp(b); \ - if (e != -1) close(e); \ - e = (e == -1); } - -#else -#define LUA_TMPNAMBUFSIZE L_tmpnam -#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } -#endif - -#endif - - -/* -@@ lua_popen spawns a new process connected to the current one through -@* the file streams. -** CHANGE it if you have a way to implement it in your system. -*/ -#if defined(LUA_USE_POPEN) - -#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m)) -#define lua_pclose(L,file) ((void)L, (pclose(file) != -1)) - -#elif defined(LUA_WIN) - -#define lua_popen(L,c,m) ((void)L, _popen(c,m)) -#define lua_pclose(L,file) ((void)L, (_pclose(file) != -1)) - -#else - -#define lua_popen(L,c,m) ((void)((void)c, m), \ - luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0) -#define lua_pclose(L,file) ((void)((void)L, file), 0) - -#endif - -/* -@@ LUA_DL_* define which dynamic-library system Lua should use. -** CHANGE here if Lua has problems choosing the appropriate -** dynamic-library system for your platform (either Windows' DLL, Mac's -** dyld, or Unix's dlopen). If your system is some kind of Unix, there -** is a good chance that it has dlopen, so LUA_DL_DLOPEN will work for -** it. To use dlopen you also need to adapt the src/Makefile (probably -** adding -ldl to the linker options), so Lua does not select it -** automatically. (When you change the makefile to add -ldl, you must -** also add -DLUA_USE_DLOPEN.) -** If you do not want any kind of dynamic library, undefine all these -** options. -** By default, _WIN32 gets LUA_DL_DLL and MAC OS X gets LUA_DL_DYLD. -*/ -#if defined(LUA_USE_DLOPEN) -#define LUA_DL_DLOPEN -#endif - -#if defined(LUA_WIN) -#define LUA_DL_DLL -#endif - - -/* -@@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State -@* (the data goes just *before* the lua_State pointer). -** CHANGE (define) this if you really need that. This value must be -** a multiple of the maximum alignment required for your machine. -*/ -#define LUAI_EXTRASPACE 0 - - -/* -@@ luai_userstate* allow user-specific actions on threads. -** CHANGE them if you defined LUAI_EXTRASPACE and need to do something -** extra when a thread is created/deleted/resumed/yielded. -*/ -#define luai_userstateopen(L) ((void)L) -#define luai_userstateclose(L) ((void)L) -#define luai_userstatethread(L,L1) ((void)L) -#define luai_userstatefree(L) ((void)L) -#define luai_userstateresume(L,n) ((void)L) -#define luai_userstateyield(L,n) ((void)L) - - -/* -@@ LUA_INTFRMLEN is the length modifier for integer conversions -@* in 'string.format'. -@@ LUA_INTFRM_T is the integer type correspoding to the previous length -@* modifier. -** CHANGE them if your system supports long long or does not support long. -*/ - -#if defined(LUA_USELONGLONG) - -#define LUA_INTFRMLEN "ll" -#define LUA_INTFRM_T long long - -#else - -#define LUA_INTFRMLEN "l" -#define LUA_INTFRM_T long - -#endif - - - -/* =================================================================== */ - -/* -** Local configuration. You can use this space to add your redefinitions -** without modifying the main part of the file. -*/ - - - -#endif - diff --git a/lua/lua51/lualib.h b/lua/lua51/lualib.h deleted file mode 100644 index 469417f..0000000 --- a/lua/lua51/lualib.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -** $Id: lualib.h,v 1.36.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lua standard libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lualib_h -#define lualib_h - -#include "lua.h" - - -/* Key to file-handle type */ -#define LUA_FILEHANDLE "FILE*" - - -#define LUA_COLIBNAME "coroutine" -LUALIB_API int (luaopen_base) (lua_State *L); - -#define LUA_TABLIBNAME "table" -LUALIB_API int (luaopen_table) (lua_State *L); - -#define LUA_IOLIBNAME "io" -LUALIB_API int (luaopen_io) (lua_State *L); - -#define LUA_OSLIBNAME "os" -LUALIB_API int (luaopen_os) (lua_State *L); - -#define LUA_STRLIBNAME "string" -LUALIB_API int (luaopen_string) (lua_State *L); - -#define LUA_MATHLIBNAME "math" -LUALIB_API int (luaopen_math) (lua_State *L); - -#define LUA_DBLIBNAME "debug" -LUALIB_API int (luaopen_debug) (lua_State *L); - -#define LUA_LOADLIBNAME "package" -LUALIB_API int (luaopen_package) (lua_State *L); - - -/* open all previous libraries */ -LUALIB_API void (luaL_openlibs) (lua_State *L); - - - -#ifndef lua_assert -#define lua_assert(x) ((void)0) -#endif - - -#endif diff --git a/lua/lua52/dummy.go b/lua/lua52/dummy.go deleted file mode 100644 index 651a797..0000000 --- a/lua/lua52/dummy.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build dummy - -// Package lua contains only a C header files. -// -// This Go file is part of a workaround for `go mod vendor`. -// Please see the file dummy.go in the parent directory for more information. -package lua diff --git a/lua/lua52/lauxlib.h b/lua/lua52/lauxlib.h deleted file mode 100644 index ac4d15f..0000000 --- a/lua/lua52/lauxlib.h +++ /dev/null @@ -1,212 +0,0 @@ -/* -** $Id: lauxlib.h,v 1.120 2011/11/29 15:55:08 roberto Exp $ -** Auxiliary functions for building Lua libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lauxlib_h -#define lauxlib_h - - -#include -#include - -#include "lua.h" - - - -/* extra error code for `luaL_load' */ -#define LUA_ERRFILE (LUA_ERRERR+1) - - -typedef struct luaL_Reg { - const char *name; - lua_CFunction func; -} luaL_Reg; - - -LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver); -#define luaL_checkversion(L) luaL_checkversion_(L, LUA_VERSION_NUM) - -LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); -LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len); -LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg); -LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg, - size_t *l); -LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg, - const char *def, size_t *l); -LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg); -LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def); - -LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg); -LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg, - lua_Integer def); -LUALIB_API lua_Unsigned (luaL_checkunsigned) (lua_State *L, int numArg); -LUALIB_API lua_Unsigned (luaL_optunsigned) (lua_State *L, int numArg, - lua_Unsigned def); - -LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); -LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t); -LUALIB_API void (luaL_checkany) (lua_State *L, int narg); - -LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); -LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); -LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); -LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); - -LUALIB_API void (luaL_where) (lua_State *L, int lvl); -LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); - -LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def, - const char *const lst[]); - -LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname); -LUALIB_API int (luaL_execresult) (lua_State *L, int stat); - -/* pre-defined references */ -#define LUA_NOREF (-2) -#define LUA_REFNIL (-1) - -LUALIB_API int (luaL_ref) (lua_State *L, int t); -LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); - -LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, - const char *mode); - -#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) - -LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, - const char *name, const char *mode); -LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); - -LUALIB_API lua_State *(luaL_newstate) (void); - -LUALIB_API int (luaL_len) (lua_State *L, int idx); - -LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, - const char *r); - -LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); - -LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname); - -LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1, - const char *msg, int level); - -LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname, - lua_CFunction openf, int glb); - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - - -#define luaL_newlibtable(L,l) \ - lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) - -#define luaL_newlib(L,l) (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) - -#define luaL_argcheck(L, cond,numarg,extramsg) \ - ((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) -#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) -#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) -#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) -#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) -#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) -#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) - -#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) - -#define luaL_dofile(L, fn) \ - (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_dostring(L, s) \ - (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) - -#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) - -#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) - - -/* -** {====================================================== -** Generic Buffer manipulation -** ======================================================= -*/ - -typedef struct luaL_Buffer { - char *b; /* buffer address */ - size_t size; /* buffer size */ - size_t n; /* number of characters in buffer */ - lua_State *L; - char initb[LUAL_BUFFERSIZE]; /* initial buffer */ -} luaL_Buffer; - - -#define luaL_addchar(B,c) \ - ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \ - ((B)->b[(B)->n++] = (c))) - -#define luaL_addsize(B,s) ((B)->n += (s)) - -LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); -LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz); -LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); -LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); -LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz); -LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz); - -#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) - -/* }====================================================== */ - - - -/* -** {====================================================== -** File handles for IO library -** ======================================================= -*/ - -/* -** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and -** initial structure 'luaL_Stream' (it may contain other fields -** after that initial structure). -*/ - -#define LUA_FILEHANDLE "FILE*" - - -typedef struct luaL_Stream { - FILE *f; /* stream (NULL for incompletely created streams) */ - lua_CFunction closef; /* to close stream (NULL for closed streams) */ -} luaL_Stream; - -/* }====================================================== */ - - - -/* compatibility with old module system */ -#if defined(LUA_COMPAT_MODULE) - -LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname, - int sizehint); -LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname, - const luaL_Reg *l, int nup); - -#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0)) - -#endif - - -#endif - - diff --git a/lua/lua52/lua.h b/lua/lua52/lua.h deleted file mode 100644 index f9800fc..0000000 --- a/lua/lua52/lua.h +++ /dev/null @@ -1,444 +0,0 @@ -/* -** $Id: lua.h,v 1.285 2013/03/15 13:04:22 roberto Exp $ -** Lua - A Scripting Language -** Lua.org, PUC-Rio, Brazil (http://www.lua.org) -** See Copyright Notice at the end of this file -*/ - - -#ifndef lua_h -#define lua_h - -#include -#include - - -#include "luaconf.h" - - -#define LUA_VERSION_MAJOR "5" -#define LUA_VERSION_MINOR "2" -#define LUA_VERSION_NUM 502 -#define LUA_VERSION_RELEASE "2" - -#define LUA_VERSION "Lua 5.2" -#define LUA_RELEASE "Lua 5.2.2" -#define LUA_COPYRIGHT "Lua 5.2.2 Copyright (C) 1994-2013 Lua.org, PUC-Rio" -#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" - - -/* mark for precompiled code ('Lua') */ -#define LUA_SIGNATURE "\033Lua" - -/* option for multiple returns in 'lua_pcall' and 'lua_call' */ -#define LUA_MULTRET (-1) - - -/* -** pseudo-indices -*/ -#define LUA_REGISTRYINDEX LUAI_FIRSTPSEUDOIDX -#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) - - -/* thread status */ -#define LUA_OK 0 -#define LUA_YIELD 1 -#define LUA_ERRRUN 2 -#define LUA_ERRSYNTAX 3 -#define LUA_ERRMEM 4 -#define LUA_ERRGCMM 5 -#define LUA_ERRERR 6 - - -typedef struct lua_State lua_State; - -typedef int (*lua_CFunction) (lua_State *L); - - -/* -** functions that read/write blocks when loading/dumping Lua chunks -*/ -typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); - -typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); - - -/* -** prototype for memory-allocation functions -*/ -typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); - - -/* -** basic types -*/ -#define LUA_TNONE (-1) - -#define LUA_TNIL 0 -#define LUA_TBOOLEAN 1 -#define LUA_TLIGHTUSERDATA 2 -#define LUA_TNUMBER 3 -#define LUA_TSTRING 4 -#define LUA_TTABLE 5 -#define LUA_TFUNCTION 6 -#define LUA_TUSERDATA 7 -#define LUA_TTHREAD 8 - -#define LUA_NUMTAGS 9 - - - -/* minimum Lua stack available to a C function */ -#define LUA_MINSTACK 20 - - -/* predefined values in the registry */ -#define LUA_RIDX_MAINTHREAD 1 -#define LUA_RIDX_GLOBALS 2 -#define LUA_RIDX_LAST LUA_RIDX_GLOBALS - - -/* type of numbers in Lua */ -typedef LUA_NUMBER lua_Number; - - -/* type for integer functions */ -typedef LUA_INTEGER lua_Integer; - -/* unsigned integer type */ -typedef LUA_UNSIGNED lua_Unsigned; - - - -/* -** generic extra include file -*/ -#if defined(LUA_USER_H) -#include LUA_USER_H -#endif - - -/* -** RCS ident string -*/ -extern const char lua_ident[]; - - -/* -** state manipulation -*/ -LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); -LUA_API void (lua_close) (lua_State *L); -LUA_API lua_State *(lua_newthread) (lua_State *L); - -LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); - - -LUA_API const lua_Number *(lua_version) (lua_State *L); - - -/* -** basic stack manipulation -*/ -LUA_API int (lua_absindex) (lua_State *L, int idx); -LUA_API int (lua_gettop) (lua_State *L); -LUA_API void (lua_settop) (lua_State *L, int idx); -LUA_API void (lua_pushvalue) (lua_State *L, int idx); -LUA_API void (lua_remove) (lua_State *L, int idx); -LUA_API void (lua_insert) (lua_State *L, int idx); -LUA_API void (lua_replace) (lua_State *L, int idx); -LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx); -LUA_API int (lua_checkstack) (lua_State *L, int sz); - -LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); - - -/* -** access functions (stack -> C) -*/ - -LUA_API int (lua_isnumber) (lua_State *L, int idx); -LUA_API int (lua_isstring) (lua_State *L, int idx); -LUA_API int (lua_iscfunction) (lua_State *L, int idx); -LUA_API int (lua_isuserdata) (lua_State *L, int idx); -LUA_API int (lua_type) (lua_State *L, int idx); -LUA_API const char *(lua_typename) (lua_State *L, int tp); - -LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum); -LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum); -LUA_API lua_Unsigned (lua_tounsignedx) (lua_State *L, int idx, int *isnum); -LUA_API int (lua_toboolean) (lua_State *L, int idx); -LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); -LUA_API size_t (lua_rawlen) (lua_State *L, int idx); -LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); -LUA_API void *(lua_touserdata) (lua_State *L, int idx); -LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); -LUA_API const void *(lua_topointer) (lua_State *L, int idx); - - -/* -** Comparison and arithmetic functions -*/ - -#define LUA_OPADD 0 /* ORDER TM */ -#define LUA_OPSUB 1 -#define LUA_OPMUL 2 -#define LUA_OPDIV 3 -#define LUA_OPMOD 4 -#define LUA_OPPOW 5 -#define LUA_OPUNM 6 - -LUA_API void (lua_arith) (lua_State *L, int op); - -#define LUA_OPEQ 0 -#define LUA_OPLT 1 -#define LUA_OPLE 2 - -LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op); - - -/* -** push functions (C -> stack) -*/ -LUA_API void (lua_pushnil) (lua_State *L); -LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); -LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); -LUA_API void (lua_pushunsigned) (lua_State *L, lua_Unsigned n); -LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t l); -LUA_API const char *(lua_pushstring) (lua_State *L, const char *s); -LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, - va_list argp); -LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); -LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); -LUA_API void (lua_pushboolean) (lua_State *L, int b); -LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); -LUA_API int (lua_pushthread) (lua_State *L); - - -/* -** get functions (Lua -> stack) -*/ -LUA_API void (lua_getglobal) (lua_State *L, const char *var); -LUA_API void (lua_gettable) (lua_State *L, int idx); -LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawget) (lua_State *L, int idx); -LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); -LUA_API void (lua_rawgetp) (lua_State *L, int idx, const void *p); -LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); -LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); -LUA_API int (lua_getmetatable) (lua_State *L, int objindex); -LUA_API void (lua_getuservalue) (lua_State *L, int idx); - - -/* -** set functions (stack -> Lua) -*/ -LUA_API void (lua_setglobal) (lua_State *L, const char *var); -LUA_API void (lua_settable) (lua_State *L, int idx); -LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawset) (lua_State *L, int idx); -LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); -LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p); -LUA_API int (lua_setmetatable) (lua_State *L, int objindex); -LUA_API void (lua_setuservalue) (lua_State *L, int idx); - - -/* -** 'load' and 'call' functions (load and run Lua code) -*/ -LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults, int ctx, - lua_CFunction k); -#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) - -LUA_API int (lua_getctx) (lua_State *L, int *ctx); - -LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc, - int ctx, lua_CFunction k); -#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) - -LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname, - const char *mode); - -LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); - - -/* -** coroutine functions -*/ -LUA_API int (lua_yieldk) (lua_State *L, int nresults, int ctx, - lua_CFunction k); -#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) -LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg); -LUA_API int (lua_status) (lua_State *L); - -/* -** garbage-collection function and options -*/ - -#define LUA_GCSTOP 0 -#define LUA_GCRESTART 1 -#define LUA_GCCOLLECT 2 -#define LUA_GCCOUNT 3 -#define LUA_GCCOUNTB 4 -#define LUA_GCSTEP 5 -#define LUA_GCSETPAUSE 6 -#define LUA_GCSETSTEPMUL 7 -#define LUA_GCSETMAJORINC 8 -#define LUA_GCISRUNNING 9 -#define LUA_GCGEN 10 -#define LUA_GCINC 11 - -LUA_API int (lua_gc) (lua_State *L, int what, int data); - - -/* -** miscellaneous functions -*/ - -LUA_API int (lua_error) (lua_State *L); - -LUA_API int (lua_next) (lua_State *L, int idx); - -LUA_API void (lua_concat) (lua_State *L, int n); -LUA_API void (lua_len) (lua_State *L, int idx); - -LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); -LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud); - - - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - -#define lua_tonumber(L,i) lua_tonumberx(L,i,NULL) -#define lua_tointeger(L,i) lua_tointegerx(L,i,NULL) -#define lua_tounsigned(L,i) lua_tounsignedx(L,i,NULL) - -#define lua_pop(L,n) lua_settop(L, -(n)-1) - -#define lua_newtable(L) lua_createtable(L, 0, 0) - -#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) - -#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) - -#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) -#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) -#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) -#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) -#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) -#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) -#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) -#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) - -#define lua_pushliteral(L, s) \ - lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) - -#define lua_pushglobaltable(L) \ - lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS) - -#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) - - - -/* -** {====================================================================== -** Debug API -** ======================================================================= -*/ - - -/* -** Event codes -*/ -#define LUA_HOOKCALL 0 -#define LUA_HOOKRET 1 -#define LUA_HOOKLINE 2 -#define LUA_HOOKCOUNT 3 -#define LUA_HOOKTAILCALL 4 - - -/* -** Event masks -*/ -#define LUA_MASKCALL (1 << LUA_HOOKCALL) -#define LUA_MASKRET (1 << LUA_HOOKRET) -#define LUA_MASKLINE (1 << LUA_HOOKLINE) -#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) - -typedef struct lua_Debug lua_Debug; /* activation record */ - - -/* Functions to be called by the debugger in specific events */ -typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); - - -LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar); -LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar); -LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n); -LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n); - -LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n); -LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1, - int fidx2, int n2); - -LUA_API int (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count); -LUA_API lua_Hook (lua_gethook) (lua_State *L); -LUA_API int (lua_gethookmask) (lua_State *L); -LUA_API int (lua_gethookcount) (lua_State *L); - - -struct lua_Debug { - int event; - const char *name; /* (n) */ - const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */ - const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */ - const char *source; /* (S) */ - int currentline; /* (l) */ - int linedefined; /* (S) */ - int lastlinedefined; /* (S) */ - unsigned char nups; /* (u) number of upvalues */ - unsigned char nparams;/* (u) number of parameters */ - char isvararg; /* (u) */ - char istailcall; /* (t) */ - char short_src[LUA_IDSIZE]; /* (S) */ - /* private part */ - struct CallInfo *i_ci; /* active function */ -}; - -/* }====================================================================== */ - - -/****************************************************************************** -* Copyright (C) 1994-2013 Lua.org, PUC-Rio. -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ - - -#endif diff --git a/lua/lua52/luaconf.h b/lua/lua52/luaconf.h deleted file mode 100644 index df802c9..0000000 --- a/lua/lua52/luaconf.h +++ /dev/null @@ -1,551 +0,0 @@ -/* -** $Id: luaconf.h,v 1.176 2013/03/16 21:10:18 roberto Exp $ -** Configuration file for Lua -** See Copyright Notice in lua.h -*/ - - -#ifndef lconfig_h -#define lconfig_h - -#include -#include - - -/* -** ================================================================== -** Search for "@@" to find all configurable definitions. -** =================================================================== -*/ - - -/* -@@ LUA_ANSI controls the use of non-ansi features. -** CHANGE it (define it) if you want Lua to avoid the use of any -** non-ansi feature or library. -*/ -#if !defined(LUA_ANSI) && defined(__STRICT_ANSI__) -#define LUA_ANSI -#endif - - -#if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE) -#define LUA_WIN /* enable goodies for regular Windows platforms */ -#endif - -#if defined(LUA_WIN) -#define LUA_DL_DLL -#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */ -#endif - - - -#if defined(LUA_USE_LINUX) -#define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ -#define LUA_USE_READLINE /* needs some extra libraries */ -#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */ -#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */ -#define LUA_USE_LONGLONG /* assume support for long long */ -#endif - -#if defined(LUA_USE_MACOSX) -#define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* does not need -ldl */ -#define LUA_USE_READLINE /* needs an extra library: -lreadline */ -#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */ -#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */ -#define LUA_USE_LONGLONG /* assume support for long long */ -#endif - - - -/* -@@ LUA_USE_POSIX includes all functionality listed as X/Open System -@* Interfaces Extension (XSI). -** CHANGE it (define it) if your system is XSI compatible. -*/ -#if defined(LUA_USE_POSIX) -#define LUA_USE_MKSTEMP -#define LUA_USE_ISATTY -#define LUA_USE_POPEN -#define LUA_USE_ULONGJMP -#define LUA_USE_GMTIME_R -#endif - - - -/* -@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for -@* Lua libraries. -@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for -@* C libraries. -** CHANGE them if your machine has a non-conventional directory -** hierarchy or if you want to install your libraries in -** non-conventional directories. -*/ -#if defined(_WIN32) /* { */ -/* -** In Windows, any exclamation mark ('!') in the path is replaced by the -** path of the directory of the executable file of the current process. -*/ -#define LUA_LDIR "!\\lua\\" -#define LUA_CDIR "!\\" -#define LUA_PATH_DEFAULT \ - LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" ".\\?.lua" -#define LUA_CPATH_DEFAULT \ - LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll;" ".\\?.dll" - -#else /* }{ */ - -#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "/" -#define LUA_ROOT "/usr/local/" -#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR -#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR -#define LUA_PATH_DEFAULT \ - LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" "./?.lua" -#define LUA_CPATH_DEFAULT \ - LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" -#endif /* } */ - - -/* -@@ LUA_DIRSEP is the directory separator (for submodules). -** CHANGE it if your machine does not use "/" as the directory separator -** and is not Windows. (On Windows Lua automatically uses "\".) -*/ -#if defined(_WIN32) -#define LUA_DIRSEP "\\" -#else -#define LUA_DIRSEP "/" -#endif - - -/* -@@ LUA_ENV is the name of the variable that holds the current -@@ environment, used to access global names. -** CHANGE it if you do not like this name. -*/ -#define LUA_ENV "_ENV" - - -/* -@@ LUA_API is a mark for all core API functions. -@@ LUALIB_API is a mark for all auxiliary library functions. -@@ LUAMOD_API is a mark for all standard library opening functions. -** CHANGE them if you need to define those functions in some special way. -** For instance, if you want to create one Windows DLL with the core and -** the libraries, you may want to use the following definition (define -** LUA_BUILD_AS_DLL to get it). -*/ -#if defined(LUA_BUILD_AS_DLL) /* { */ - -#if defined(LUA_CORE) || defined(LUA_LIB) /* { */ -#define LUA_API __declspec(dllexport) -#else /* }{ */ -#define LUA_API __declspec(dllimport) -#endif /* } */ - -#else /* }{ */ - -#define LUA_API extern - -#endif /* } */ - - -/* more often than not the libs go together with the core */ -#define LUALIB_API LUA_API -#define LUAMOD_API LUALIB_API - - -/* -@@ LUAI_FUNC is a mark for all extern functions that are not to be -@* exported to outside modules. -@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables -@* that are not to be exported to outside modules (LUAI_DDEF for -@* definitions and LUAI_DDEC for declarations). -** CHANGE them if you need to mark them in some special way. Elf/gcc -** (versions 3.2 and later) mark them as "hidden" to optimize access -** when Lua is compiled as a shared library. Not all elf targets support -** this attribute. Unfortunately, gcc does not offer a way to check -** whether the target offers that support, and those without support -** give a warning about it. To avoid these warnings, change to the -** default definition. -*/ -#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ - defined(__ELF__) /* { */ -#define LUAI_FUNC __attribute__((visibility("hidden"))) extern -#define LUAI_DDEC LUAI_FUNC -#define LUAI_DDEF /* empty */ - -#else /* }{ */ -#define LUAI_FUNC extern -#define LUAI_DDEC extern -#define LUAI_DDEF /* empty */ -#endif /* } */ - - - -/* -@@ LUA_QL describes how error messages quote program elements. -** CHANGE it if you want a different appearance. -*/ -#define LUA_QL(x) "'" x "'" -#define LUA_QS LUA_QL("%s") - - -/* -@@ LUA_IDSIZE gives the maximum size for the description of the source -@* of a function in debug information. -** CHANGE it if you want a different size. -*/ -#define LUA_IDSIZE 60 - - -/* -@@ luai_writestring/luai_writeline define how 'print' prints its results. -** They are only used in libraries and the stand-alone program. (The #if -** avoids including 'stdio.h' everywhere.) -*/ -#if defined(LUA_LIB) || defined(lua_c) -#include -#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) -#define luai_writeline() (luai_writestring("\n", 1), fflush(stdout)) -#endif - -/* -@@ luai_writestringerror defines how to print error messages. -** (A format string with one argument is enough for Lua...) -*/ -#define luai_writestringerror(s,p) \ - (fprintf(stderr, (s), (p)), fflush(stderr)) - - -/* -@@ LUAI_MAXSHORTLEN is the maximum length for short strings, that is, -** strings that are internalized. (Cannot be smaller than reserved words -** or tags for metamethods, as these strings must be internalized; -** #("function") = 8, #("__newindex") = 10.) -*/ -#define LUAI_MAXSHORTLEN 40 - - - -/* -** {================================================================== -** Compatibility with previous versions -** =================================================================== -*/ - -/* -@@ LUA_COMPAT_ALL controls all compatibility options. -** You can define it to get all options, or change specific options -** to fit your specific needs. -*/ -#if defined(LUA_COMPAT_ALL) /* { */ - -/* -@@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'. -** You can replace it with 'table.unpack'. -*/ -#define LUA_COMPAT_UNPACK - -/* -@@ LUA_COMPAT_LOADERS controls the presence of table 'package.loaders'. -** You can replace it with 'package.searchers'. -*/ -#define LUA_COMPAT_LOADERS - -/* -@@ macro 'lua_cpcall' emulates deprecated function lua_cpcall. -** You can call your C function directly (with light C functions). -*/ -#define lua_cpcall(L,f,u) \ - (lua_pushcfunction(L, (f)), \ - lua_pushlightuserdata(L,(u)), \ - lua_pcall(L,1,0,0)) - - -/* -@@ LUA_COMPAT_LOG10 defines the function 'log10' in the math library. -** You can rewrite 'log10(x)' as 'log(x, 10)'. -*/ -#define LUA_COMPAT_LOG10 - -/* -@@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base -** library. You can rewrite 'loadstring(s)' as 'load(s)'. -*/ -#define LUA_COMPAT_LOADSTRING - -/* -@@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library. -*/ -#define LUA_COMPAT_MAXN - -/* -@@ The following macros supply trivial compatibility for some -** changes in the API. The macros themselves document how to -** change your code to avoid using them. -*/ -#define lua_strlen(L,i) lua_rawlen(L, (i)) - -#define lua_objlen(L,i) lua_rawlen(L, (i)) - -#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) -#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) - -/* -@@ LUA_COMPAT_MODULE controls compatibility with previous -** module functions 'module' (Lua) and 'luaL_register' (C). -*/ -#define LUA_COMPAT_MODULE - -#endif /* } */ - -/* }================================================================== */ - - - -/* -@@ LUAI_BITSINT defines the number of bits in an int. -** CHANGE here if Lua cannot automatically detect the number of bits of -** your machine. Probably you do not need to change this. -*/ -/* avoid overflows in comparison */ -#if INT_MAX-20 < 32760 /* { */ -#define LUAI_BITSINT 16 -#elif INT_MAX > 2147483640L /* }{ */ -/* int has at least 32 bits */ -#define LUAI_BITSINT 32 -#else /* }{ */ -#error "you must define LUA_BITSINT with number of bits in an integer" -#endif /* } */ - - -/* -@@ LUA_INT32 is an signed integer with exactly 32 bits. -@@ LUAI_UMEM is an unsigned integer big enough to count the total -@* memory used by Lua. -@@ LUAI_MEM is a signed integer big enough to count the total memory -@* used by Lua. -** CHANGE here if for some weird reason the default definitions are not -** good enough for your machine. Probably you do not need to change -** this. -*/ -#if LUAI_BITSINT >= 32 /* { */ -#define LUA_INT32 int -#define LUAI_UMEM size_t -#define LUAI_MEM ptrdiff_t -#else /* }{ */ -/* 16-bit ints */ -#define LUA_INT32 long -#define LUAI_UMEM unsigned long -#define LUAI_MEM long -#endif /* } */ - - -/* -@@ LUAI_MAXSTACK limits the size of the Lua stack. -** CHANGE it if you need a different limit. This limit is arbitrary; -** its only purpose is to stop Lua to consume unlimited stack -** space (and to reserve some numbers for pseudo-indices). -*/ -#if LUAI_BITSINT >= 32 -#define LUAI_MAXSTACK 1000000 -#else -#define LUAI_MAXSTACK 15000 -#endif - -/* reserve some space for error handling */ -#define LUAI_FIRSTPSEUDOIDX (-LUAI_MAXSTACK - 1000) - - - - -/* -@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. -** CHANGE it if it uses too much C-stack space. -*/ -#define LUAL_BUFFERSIZE BUFSIZ - - - - -/* -** {================================================================== -@@ LUA_NUMBER is the type of numbers in Lua. -** CHANGE the following definitions only if you want to build Lua -** with a number type different from double. You may also need to -** change lua_number2int & lua_number2integer. -** =================================================================== -*/ - -#define LUA_NUMBER_DOUBLE -#define LUA_NUMBER double - -/* -@@ LUAI_UACNUMBER is the result of an 'usual argument conversion' -@* over a number. -*/ -#define LUAI_UACNUMBER double - - -/* -@@ LUA_NUMBER_SCAN is the format for reading numbers. -@@ LUA_NUMBER_FMT is the format for writing numbers. -@@ lua_number2str converts a number to a string. -@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion. -*/ -#define LUA_NUMBER_SCAN "%lf" -#define LUA_NUMBER_FMT "%.14g" -#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) -#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */ - - -/* -@@ l_mathop allows the addition of an 'l' or 'f' to all math operations -*/ -#define l_mathop(x) (x) - - -/* -@@ lua_str2number converts a decimal numeric string to a number. -@@ lua_strx2number converts an hexadecimal numeric string to a number. -** In C99, 'strtod' does both conversions. C89, however, has no function -** to convert floating hexadecimal strings to numbers. For these -** systems, you can leave 'lua_strx2number' undefined and Lua will -** provide its own implementation. -*/ -#define lua_str2number(s,p) strtod((s), (p)) - -#if defined(LUA_USE_STRTODHEX) -#define lua_strx2number(s,p) strtod((s), (p)) -#endif - - -/* -@@ The luai_num* macros define the primitive operations over numbers. -*/ - -/* the following operations need the math library */ -#if defined(lobject_c) || defined(lvm_c) -#include -#define luai_nummod(L,a,b) ((a) - l_mathop(floor)((a)/(b))*(b)) -#define luai_numpow(L,a,b) (l_mathop(pow)(a,b)) -#endif - -/* these are quite standard operations */ -#if defined(LUA_CORE) -#define luai_numadd(L,a,b) ((a)+(b)) -#define luai_numsub(L,a,b) ((a)-(b)) -#define luai_nummul(L,a,b) ((a)*(b)) -#define luai_numdiv(L,a,b) ((a)/(b)) -#define luai_numunm(L,a) (-(a)) -#define luai_numeq(a,b) ((a)==(b)) -#define luai_numlt(L,a,b) ((a)<(b)) -#define luai_numle(L,a,b) ((a)<=(b)) -#define luai_numisnan(L,a) (!luai_numeq((a), (a))) -#endif - - - -/* -@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger. -** CHANGE that if ptrdiff_t is not adequate on your machine. (On most -** machines, ptrdiff_t gives a good choice between int or long.) -*/ -#define LUA_INTEGER ptrdiff_t - -/* -@@ LUA_UNSIGNED is the integral type used by lua_pushunsigned/lua_tounsigned. -** It must have at least 32 bits. -*/ -#define LUA_UNSIGNED unsigned LUA_INT32 - - - -/* -** Some tricks with doubles -*/ - -#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) /* { */ -/* -** The next definitions activate some tricks to speed up the -** conversion from doubles to integer types, mainly to LUA_UNSIGNED. -** -@@ LUA_MSASMTRICK uses Microsoft assembler to avoid clashes with a -** DirectX idiosyncrasy. -** -@@ LUA_IEEE754TRICK uses a trick that should work on any machine -** using IEEE754 with a 32-bit integer type. -** -@@ LUA_IEEELL extends the trick to LUA_INTEGER; should only be -** defined when LUA_INTEGER is a 32-bit integer. -** -@@ LUA_IEEEENDIAN is the endianness of doubles in your machine -** (0 for little endian, 1 for big endian); if not defined, Lua will -** check it dynamically for LUA_IEEE754TRICK (but not for LUA_NANTRICK). -** -@@ LUA_NANTRICK controls the use of a trick to pack all types into -** a single double value, using NaN values to represent non-number -** values. The trick only works on 32-bit machines (ints and pointers -** are 32-bit values) with numbers represented as IEEE 754-2008 doubles -** with conventional endianess (12345678 or 87654321), in CPUs that do -** not produce signaling NaN values (all NaNs are quiet). -*/ - -/* Microsoft compiler on a Pentium (32 bit) ? */ -#if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86) /* { */ - -#define LUA_MSASMTRICK -#define LUA_IEEEENDIAN 0 -#define LUA_NANTRICK - - -/* pentium 32 bits? */ -#elif defined(__i386__) || defined(__i386) || defined(__X86__) /* }{ */ - -#define LUA_IEEE754TRICK -#define LUA_IEEELL -#define LUA_IEEEENDIAN 0 -#define LUA_NANTRICK - -/* pentium 64 bits? */ -#elif defined(__x86_64) /* }{ */ - -#define LUA_IEEE754TRICK -#define LUA_IEEEENDIAN 0 - -#elif defined(__POWERPC__) || defined(__ppc__) /* }{ */ - -#define LUA_IEEE754TRICK -#define LUA_IEEEENDIAN 1 - -#else /* }{ */ - -/* assume IEEE754 and a 32-bit integer type */ -#define LUA_IEEE754TRICK - -#endif /* } */ - -#endif /* } */ - -/* }================================================================== */ - - - - -/* =================================================================== */ - -/* -** Local configuration. You can use this space to add your redefinitions -** without modifying the main part of the file. -*/ - - - -#endif - diff --git a/lua/lua52/lualib.h b/lua/lua52/lualib.h deleted file mode 100644 index 9fd126b..0000000 --- a/lua/lua52/lualib.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -** $Id: lualib.h,v 1.43 2011/12/08 12:11:37 roberto Exp $ -** Lua standard libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lualib_h -#define lualib_h - -#include "lua.h" - - - -LUAMOD_API int (luaopen_base) (lua_State *L); - -#define LUA_COLIBNAME "coroutine" -LUAMOD_API int (luaopen_coroutine) (lua_State *L); - -#define LUA_TABLIBNAME "table" -LUAMOD_API int (luaopen_table) (lua_State *L); - -#define LUA_IOLIBNAME "io" -LUAMOD_API int (luaopen_io) (lua_State *L); - -#define LUA_OSLIBNAME "os" -LUAMOD_API int (luaopen_os) (lua_State *L); - -#define LUA_STRLIBNAME "string" -LUAMOD_API int (luaopen_string) (lua_State *L); - -#define LUA_BITLIBNAME "bit32" -LUAMOD_API int (luaopen_bit32) (lua_State *L); - -#define LUA_MATHLIBNAME "math" -LUAMOD_API int (luaopen_math) (lua_State *L); - -#define LUA_DBLIBNAME "debug" -LUAMOD_API int (luaopen_debug) (lua_State *L); - -#define LUA_LOADLIBNAME "package" -LUAMOD_API int (luaopen_package) (lua_State *L); - - -/* open all previous libraries */ -LUALIB_API void (luaL_openlibs) (lua_State *L); - - - -#if !defined(lua_assert) -#define lua_assert(x) ((void)0) -#endif - - -#endif diff --git a/lua/lua53/dummy.go b/lua/lua53/dummy.go deleted file mode 100644 index 651a797..0000000 --- a/lua/lua53/dummy.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build dummy - -// Package lua contains only a C header files. -// -// This Go file is part of a workaround for `go mod vendor`. -// Please see the file dummy.go in the parent directory for more information. -package lua diff --git a/lua/lua53/lauxlib.h b/lua/lua53/lauxlib.h deleted file mode 100644 index 0bac246..0000000 --- a/lua/lua53/lauxlib.h +++ /dev/null @@ -1,256 +0,0 @@ -/* -** $Id: lauxlib.h,v 1.128 2014/10/29 16:11:17 roberto Exp $ -** Auxiliary functions for building Lua libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lauxlib_h -#define lauxlib_h - - -#include -#include - -#include "lua.h" - - - -/* extra error code for 'luaL_load' */ -#define LUA_ERRFILE (LUA_ERRERR+1) - - -typedef struct luaL_Reg { - const char *name; - lua_CFunction func; -} luaL_Reg; - - -#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number)) - -LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz); -#define luaL_checkversion(L) \ - luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES) - -LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); -LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len); -LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg); -LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg, - size_t *l); -LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg, - const char *def, size_t *l); -LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg); -LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def); - -LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg); -LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg, - lua_Integer def); - -LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); -LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t); -LUALIB_API void (luaL_checkany) (lua_State *L, int arg); - -LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); -LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); -LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); -LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); - -LUALIB_API void (luaL_where) (lua_State *L, int lvl); -LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); - -LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def, - const char *const lst[]); - -LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname); -LUALIB_API int (luaL_execresult) (lua_State *L, int stat); - -/* pre-defined references */ -#define LUA_NOREF (-2) -#define LUA_REFNIL (-1) - -LUALIB_API int (luaL_ref) (lua_State *L, int t); -LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); - -LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, - const char *mode); - -#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) - -LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, - const char *name, const char *mode); -LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); - -LUALIB_API lua_State *(luaL_newstate) (void); - -LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx); - -LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, - const char *r); - -LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); - -LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname); - -LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1, - const char *msg, int level); - -LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname, - lua_CFunction openf, int glb); - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - - -#define luaL_newlibtable(L,l) \ - lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) - -#define luaL_newlib(L,l) \ - (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) - -#define luaL_argcheck(L, cond,arg,extramsg) \ - ((void)((cond) || luaL_argerror(L, (arg), (extramsg)))) -#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) -#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) - -#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) - -#define luaL_dofile(L, fn) \ - (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_dostring(L, s) \ - (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) - -#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) - -#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) - - -/* -** {====================================================== -** Generic Buffer manipulation -** ======================================================= -*/ - -typedef struct luaL_Buffer { - char *b; /* buffer address */ - size_t size; /* buffer size */ - size_t n; /* number of characters in buffer */ - lua_State *L; - char initb[LUAL_BUFFERSIZE]; /* initial buffer */ -} luaL_Buffer; - - -#define luaL_addchar(B,c) \ - ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \ - ((B)->b[(B)->n++] = (c))) - -#define luaL_addsize(B,s) ((B)->n += (s)) - -LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); -LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz); -LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); -LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); -LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz); -LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz); - -#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) - -/* }====================================================== */ - - - -/* -** {====================================================== -** File handles for IO library -** ======================================================= -*/ - -/* -** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and -** initial structure 'luaL_Stream' (it may contain other fields -** after that initial structure). -*/ - -#define LUA_FILEHANDLE "FILE*" - - -typedef struct luaL_Stream { - FILE *f; /* stream (NULL for incompletely created streams) */ - lua_CFunction closef; /* to close stream (NULL for closed streams) */ -} luaL_Stream; - -/* }====================================================== */ - - - -/* compatibility with old module system */ -#if defined(LUA_COMPAT_MODULE) - -LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname, - int sizehint); -LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname, - const luaL_Reg *l, int nup); - -#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0)) - -#endif - - -/* -** {================================================================== -** "Abstraction Layer" for basic report of messages and errors -** =================================================================== -*/ - -/* print a string */ -#if !defined(lua_writestring) -#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) -#endif - -/* print a newline and flush the output */ -#if !defined(lua_writeline) -#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout)) -#endif - -/* print an error message */ -#if !defined(lua_writestringerror) -#define lua_writestringerror(s,p) \ - (fprintf(stderr, (s), (p)), fflush(stderr)) -#endif - -/* }================================================================== */ - - -/* -** {============================================================ -** Compatibility with deprecated conversions -** ============================================================= -*/ -#if defined(LUA_COMPAT_APIINTCASTS) - -#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a)) -#define luaL_optunsigned(L,a,d) \ - ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d))) - -#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) -#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) - -#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) -#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) - -#endif -/* }============================================================ */ - - - -#endif - - diff --git a/lua/lua53/lua.h b/lua/lua53/lua.h deleted file mode 100644 index 6ae3112..0000000 --- a/lua/lua53/lua.h +++ /dev/null @@ -1,486 +0,0 @@ -/* -** $Id: lua.h,v 1.328 2015/06/03 13:03:38 roberto Exp $ -** Lua - A Scripting Language -** Lua.org, PUC-Rio, Brazil (http://www.lua.org) -** See Copyright Notice at the end of this file -*/ - - -#ifndef lua_h -#define lua_h - -#include -#include - - -#include "luaconf.h" - - -#define LUA_VERSION_MAJOR "5" -#define LUA_VERSION_MINOR "3" -#define LUA_VERSION_NUM 503 -#define LUA_VERSION_RELEASE "1" - -#define LUA_VERSION "Lua 5.3" -#define LUA_RELEASE "Lua 5.3.1" -#define LUA_COPYRIGHT "Lua 5.3.1 Copyright (C) 1994-2015 Lua.org, PUC-Rio" -#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" - - -/* mark for precompiled code ('Lua') */ -#define LUA_SIGNATURE "\x1bLua" - -/* option for multiple returns in 'lua_pcall' and 'lua_call' */ -#define LUA_MULTRET (-1) - - -/* -** Pseudo-indices -** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty -** space after that to help overflow detection) -*/ -#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000) -#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) - - -/* thread status */ -#define LUA_OK 0 -#define LUA_YIELD 1 -#define LUA_ERRRUN 2 -#define LUA_ERRSYNTAX 3 -#define LUA_ERRMEM 4 -#define LUA_ERRGCMM 5 -#define LUA_ERRERR 6 - - -typedef struct lua_State lua_State; - - -/* -** basic types -*/ -#define LUA_TNONE (-1) - -#define LUA_TNIL 0 -#define LUA_TBOOLEAN 1 -#define LUA_TLIGHTUSERDATA 2 -#define LUA_TNUMBER 3 -#define LUA_TSTRING 4 -#define LUA_TTABLE 5 -#define LUA_TFUNCTION 6 -#define LUA_TUSERDATA 7 -#define LUA_TTHREAD 8 - -#define LUA_NUMTAGS 9 - - - -/* minimum Lua stack available to a C function */ -#define LUA_MINSTACK 20 - - -/* predefined values in the registry */ -#define LUA_RIDX_MAINTHREAD 1 -#define LUA_RIDX_GLOBALS 2 -#define LUA_RIDX_LAST LUA_RIDX_GLOBALS - - -/* type of numbers in Lua */ -typedef LUA_NUMBER lua_Number; - - -/* type for integer functions */ -typedef LUA_INTEGER lua_Integer; - -/* unsigned integer type */ -typedef LUA_UNSIGNED lua_Unsigned; - -/* type for continuation-function contexts */ -typedef LUA_KCONTEXT lua_KContext; - - -/* -** Type for C functions registered with Lua -*/ -typedef int (*lua_CFunction) (lua_State *L); - -/* -** Type for continuation functions -*/ -typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); - - -/* -** Type for functions that read/write blocks when loading/dumping Lua chunks -*/ -typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); - -typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud); - - -/* -** Type for memory-allocation functions -*/ -typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); - - - -/* -** generic extra include file -*/ -#if defined(LUA_USER_H) -#include LUA_USER_H -#endif - - -/* -** RCS ident string -*/ -extern const char lua_ident[]; - - -/* -** state manipulation -*/ -LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); -LUA_API void (lua_close) (lua_State *L); -LUA_API lua_State *(lua_newthread) (lua_State *L); - -LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); - - -LUA_API const lua_Number *(lua_version) (lua_State *L); - - -/* -** basic stack manipulation -*/ -LUA_API int (lua_absindex) (lua_State *L, int idx); -LUA_API int (lua_gettop) (lua_State *L); -LUA_API void (lua_settop) (lua_State *L, int idx); -LUA_API void (lua_pushvalue) (lua_State *L, int idx); -LUA_API void (lua_rotate) (lua_State *L, int idx, int n); -LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx); -LUA_API int (lua_checkstack) (lua_State *L, int n); - -LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); - - -/* -** access functions (stack -> C) -*/ - -LUA_API int (lua_isnumber) (lua_State *L, int idx); -LUA_API int (lua_isstring) (lua_State *L, int idx); -LUA_API int (lua_iscfunction) (lua_State *L, int idx); -LUA_API int (lua_isinteger) (lua_State *L, int idx); -LUA_API int (lua_isuserdata) (lua_State *L, int idx); -LUA_API int (lua_type) (lua_State *L, int idx); -LUA_API const char *(lua_typename) (lua_State *L, int tp); - -LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum); -LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum); -LUA_API int (lua_toboolean) (lua_State *L, int idx); -LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); -LUA_API size_t (lua_rawlen) (lua_State *L, int idx); -LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); -LUA_API void *(lua_touserdata) (lua_State *L, int idx); -LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); -LUA_API const void *(lua_topointer) (lua_State *L, int idx); - - -/* -** Comparison and arithmetic functions -*/ - -#define LUA_OPADD 0 /* ORDER TM, ORDER OP */ -#define LUA_OPSUB 1 -#define LUA_OPMUL 2 -#define LUA_OPMOD 3 -#define LUA_OPPOW 4 -#define LUA_OPDIV 5 -#define LUA_OPIDIV 6 -#define LUA_OPBAND 7 -#define LUA_OPBOR 8 -#define LUA_OPBXOR 9 -#define LUA_OPSHL 10 -#define LUA_OPSHR 11 -#define LUA_OPUNM 12 -#define LUA_OPBNOT 13 - -LUA_API void (lua_arith) (lua_State *L, int op); - -#define LUA_OPEQ 0 -#define LUA_OPLT 1 -#define LUA_OPLE 2 - -LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op); - - -/* -** push functions (C -> stack) -*/ -LUA_API void (lua_pushnil) (lua_State *L); -LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); -LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); -LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len); -LUA_API const char *(lua_pushstring) (lua_State *L, const char *s); -LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, - va_list argp); -LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); -LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); -LUA_API void (lua_pushboolean) (lua_State *L, int b); -LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); -LUA_API int (lua_pushthread) (lua_State *L); - - -/* -** get functions (Lua -> stack) -*/ -LUA_API int (lua_getglobal) (lua_State *L, const char *name); -LUA_API int (lua_gettable) (lua_State *L, int idx); -LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k); -LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n); -LUA_API int (lua_rawget) (lua_State *L, int idx); -LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n); -LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p); - -LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); -LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); -LUA_API int (lua_getmetatable) (lua_State *L, int objindex); -LUA_API int (lua_getuservalue) (lua_State *L, int idx); - - -/* -** set functions (stack -> Lua) -*/ -LUA_API void (lua_setglobal) (lua_State *L, const char *name); -LUA_API void (lua_settable) (lua_State *L, int idx); -LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_seti) (lua_State *L, int idx, lua_Integer n); -LUA_API void (lua_rawset) (lua_State *L, int idx); -LUA_API void (lua_rawseti) (lua_State *L, int idx, lua_Integer n); -LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p); -LUA_API int (lua_setmetatable) (lua_State *L, int objindex); -LUA_API void (lua_setuservalue) (lua_State *L, int idx); - - -/* -** 'load' and 'call' functions (load and run Lua code) -*/ -LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults, - lua_KContext ctx, lua_KFunction k); -#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) - -LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc, - lua_KContext ctx, lua_KFunction k); -#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) - -LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname, const char *mode); - -LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip); - - -/* -** coroutine functions -*/ -LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx, - lua_KFunction k); -LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg); -LUA_API int (lua_status) (lua_State *L); -LUA_API int (lua_isyieldable) (lua_State *L); - -#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) - - -/* -** garbage-collection function and options -*/ - -#define LUA_GCSTOP 0 -#define LUA_GCRESTART 1 -#define LUA_GCCOLLECT 2 -#define LUA_GCCOUNT 3 -#define LUA_GCCOUNTB 4 -#define LUA_GCSTEP 5 -#define LUA_GCSETPAUSE 6 -#define LUA_GCSETSTEPMUL 7 -#define LUA_GCISRUNNING 9 - -LUA_API int (lua_gc) (lua_State *L, int what, int data); - - -/* -** miscellaneous functions -*/ - -LUA_API int (lua_error) (lua_State *L); - -LUA_API int (lua_next) (lua_State *L, int idx); - -LUA_API void (lua_concat) (lua_State *L, int n); -LUA_API void (lua_len) (lua_State *L, int idx); - -LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s); - -LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); -LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud); - - - -/* -** {============================================================== -** some useful macros -** =============================================================== -*/ - -#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE)) - -#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL) -#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL) - -#define lua_pop(L,n) lua_settop(L, -(n)-1) - -#define lua_newtable(L) lua_createtable(L, 0, 0) - -#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) - -#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) - -#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) -#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) -#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) -#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) -#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) -#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) -#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) -#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) - -#define lua_pushliteral(L, s) lua_pushstring(L, "" s) - -#define lua_pushglobaltable(L) \ - lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS) - -#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) - - -#define lua_insert(L,idx) lua_rotate(L, (idx), 1) - -#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1)) - -#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1)) - -/* }============================================================== */ - - -/* -** {============================================================== -** compatibility macros for unsigned conversions -** =============================================================== -*/ -#if defined(LUA_COMPAT_APIINTCASTS) - -#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) -#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is)) -#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL) - -#endif -/* }============================================================== */ - -/* -** {====================================================================== -** Debug API -** ======================================================================= -*/ - - -/* -** Event codes -*/ -#define LUA_HOOKCALL 0 -#define LUA_HOOKRET 1 -#define LUA_HOOKLINE 2 -#define LUA_HOOKCOUNT 3 -#define LUA_HOOKTAILCALL 4 - - -/* -** Event masks -*/ -#define LUA_MASKCALL (1 << LUA_HOOKCALL) -#define LUA_MASKRET (1 << LUA_HOOKRET) -#define LUA_MASKLINE (1 << LUA_HOOKLINE) -#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) - -typedef struct lua_Debug lua_Debug; /* activation record */ - - -/* Functions to be called by the debugger in specific events */ -typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); - - -LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar); -LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar); -LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n); -LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n); - -LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n); -LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1, - int fidx2, int n2); - -LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count); -LUA_API lua_Hook (lua_gethook) (lua_State *L); -LUA_API int (lua_gethookmask) (lua_State *L); -LUA_API int (lua_gethookcount) (lua_State *L); - - -struct lua_Debug { - int event; - const char *name; /* (n) */ - const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */ - const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */ - const char *source; /* (S) */ - int currentline; /* (l) */ - int linedefined; /* (S) */ - int lastlinedefined; /* (S) */ - unsigned char nups; /* (u) number of upvalues */ - unsigned char nparams;/* (u) number of parameters */ - char isvararg; /* (u) */ - char istailcall; /* (t) */ - char short_src[LUA_IDSIZE]; /* (S) */ - /* private part */ - struct CallInfo *i_ci; /* active function */ -}; - -/* }====================================================================== */ - - -/****************************************************************************** -* Copyright (C) 1994-2015 Lua.org, PUC-Rio. -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ - - -#endif diff --git a/lua/lua53/luaconf.h b/lua/lua53/luaconf.h deleted file mode 100644 index d1cdc48..0000000 --- a/lua/lua53/luaconf.h +++ /dev/null @@ -1,763 +0,0 @@ -/* -** $Id: luaconf.h,v 1.251 2015/05/20 17:39:23 roberto Exp $ -** Configuration file for Lua -** See Copyright Notice in lua.h -*/ - - -#ifndef luaconf_h -#define luaconf_h - -#include -#include - - -/* -** =================================================================== -** Search for "@@" to find all configurable definitions. -** =================================================================== -*/ - - -/* -** {==================================================================== -** System Configuration: macros to adapt (if needed) Lua to some -** particular platform, for instance compiling it with 32-bit numbers or -** restricting it to C89. -** ===================================================================== -*/ - -/* -@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. You -** can also define LUA_32BITS in the make file, but changing here you -** ensure that all software connected to Lua will be compiled with the -** same configuration. -*/ -/* #define LUA_32BITS */ - - -/* -@@ LUA_USE_C89 controls the use of non-ISO-C89 features. -** Define it if you want Lua to avoid the use of a few C99 features -** or Windows-specific features on Windows. -*/ -/* #define LUA_USE_C89 */ - - -/* -** By default, Lua on Windows use (some) specific Windows features -*/ -#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE) -#define LUA_USE_WINDOWS /* enable goodies for regular Windows */ -#endif - - -#if defined(LUA_USE_WINDOWS) -#define LUA_DL_DLL /* enable support for DLL */ -#define LUA_USE_C89 /* broadly, Windows is C89 */ -#endif - - -#if defined(LUA_USE_LINUX) -#define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ -#define LUA_USE_READLINE /* needs some extra libraries */ -#endif - - -#if defined(LUA_USE_MACOSX) -#define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* MacOS does not need -ldl */ -#define LUA_USE_READLINE /* needs an extra library: -lreadline */ -#endif - - -/* -@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for -** C89 ('long' and 'double'); Windows always has '__int64', so it does -** not need to use this case. -*/ -#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS) -#define LUA_C89_NUMBERS -#endif - - - -/* -@@ LUAI_BITSINT defines the (minimum) number of bits in an 'int'. -*/ -/* avoid undefined shifts */ -#if ((INT_MAX >> 15) >> 15) >= 1 -#define LUAI_BITSINT 32 -#else -/* 'int' always must have at least 16 bits */ -#define LUAI_BITSINT 16 -#endif - - -/* -@@ LUA_INT_TYPE defines the type for Lua integers. -@@ LUA_FLOAT_TYPE defines the type for Lua floats. -** Lua should work fine with any mix of these options (if supported -** by your C compiler). The usual configurations are 64-bit integers -** and 'double' (the default), 32-bit integers and 'float' (for -** restricted platforms), and 'long'/'double' (for C compilers not -** compliant with C99, which may not have support for 'long long'). -*/ - -/* predefined options for LUA_INT_TYPE */ -#define LUA_INT_INT 1 -#define LUA_INT_LONG 2 -#define LUA_INT_LONGLONG 3 - -/* predefined options for LUA_FLOAT_TYPE */ -#define LUA_FLOAT_FLOAT 1 -#define LUA_FLOAT_DOUBLE 2 -#define LUA_FLOAT_LONGDOUBLE 3 - -#if defined(LUA_32BITS) /* { */ -/* -** 32-bit integers and 'float' -*/ -#if LUAI_BITSINT >= 32 /* use 'int' if big enough */ -#define LUA_INT_TYPE LUA_INT_INT -#else /* otherwise use 'long' */ -#define LUA_INT_TYPE LUA_INT_LONG -#endif -#define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT - -#elif defined(LUA_C89_NUMBERS) /* }{ */ -/* -** largest types available for C89 ('long' and 'double') -*/ -#define LUA_INT_TYPE LUA_INT_LONG -#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE - -#endif /* } */ - - -/* -** default configuration for 64-bit Lua ('long long' and 'double') -*/ -#if !defined(LUA_INT_TYPE) -#define LUA_INT_TYPE LUA_INT_LONGLONG -#endif - -#if !defined(LUA_FLOAT_TYPE) -#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE -#endif /* } */ - -/* }================================================================== */ - - - - -/* -** {================================================================== -** Configuration for Paths. -** =================================================================== -*/ - -/* -@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for -** Lua libraries. -@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for -** C libraries. -** CHANGE them if your machine has a non-conventional directory -** hierarchy or if you want to install your libraries in -** non-conventional directories. -*/ -#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR -#if defined(_WIN32) /* { */ -/* -** In Windows, any exclamation mark ('!') in the path is replaced by the -** path of the directory of the executable file of the current process. -*/ -#define LUA_LDIR "!\\lua\\" -#define LUA_CDIR "!\\" -#define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\" -#define LUA_PATH_DEFAULT \ - LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \ - LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ - ".\\?.lua;" ".\\?\\init.lua" -#define LUA_CPATH_DEFAULT \ - LUA_CDIR"?.dll;" \ - LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \ - LUA_CDIR"loadall.dll;" ".\\?.dll" - -#else /* }{ */ - -/* This defines DEB_HOST_MULTIARCH */ -//#include "lua5.3-deb-multiarch.h" - -#define LUA_ROOT "/usr/local/" -#define LUA_ROOT2 "/usr/" -#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/" -#define LUA_LDIR2 LUA_ROOT2 "share/lua/" LUA_VDIR "/" -#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/" -#define LUA_CDIR2 LUA_ROOT2 "lib/" DEB_HOST_MULTIARCH "/lua/" LUA_VDIR "/" -#define LUA_CDIR3 LUA_ROOT2 "lib/lua/" LUA_VDIR "/" - -#define LUA_PATH_DEFAULT \ - LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \ - LUA_LDIR2"?.lua;" LUA_LDIR2"?/init.lua;" \ - "./?.lua;" "./?/init.lua" -#define LUA_CPATH_DEFAULT \ - LUA_CDIR"?.so;" LUA_CDIR2"?.so;" LUA_CDIR3"?.so;" LUA_CDIR"loadall.so;" "./?.so" -#endif /* } */ - - -/* -@@ LUA_DIRSEP is the directory separator (for submodules). -** CHANGE it if your machine does not use "/" as the directory separator -** and is not Windows. (On Windows Lua automatically uses "\".) -*/ -#if defined(_WIN32) -#define LUA_DIRSEP "\\" -#else -#define LUA_DIRSEP "/" -#endif - -/* }================================================================== */ - - -/* -** {================================================================== -** Marks for exported symbols in the C code -** =================================================================== -*/ - -/* -@@ LUA_API is a mark for all core API functions. -@@ LUALIB_API is a mark for all auxiliary library functions. -@@ LUAMOD_API is a mark for all standard library opening functions. -** CHANGE them if you need to define those functions in some special way. -** For instance, if you want to create one Windows DLL with the core and -** the libraries, you may want to use the following definition (define -** LUA_BUILD_AS_DLL to get it). -*/ -#if defined(LUA_BUILD_AS_DLL) /* { */ - -#if defined(LUA_CORE) || defined(LUA_LIB) /* { */ -#define LUA_API __declspec(dllexport) -#else /* }{ */ -#define LUA_API __declspec(dllimport) -#endif /* } */ - -#else /* }{ */ - -#ifdef __cplusplus -#define LUA_API extern "C" -#else -#define LUA_API extern -#endif - -#endif /* } */ - - -/* more often than not the libs go together with the core */ -#define LUALIB_API LUA_API -#define LUAMOD_API LUALIB_API - - -/* -@@ LUAI_FUNC is a mark for all extern functions that are not to be -** exported to outside modules. -@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables -** that are not to be exported to outside modules (LUAI_DDEF for -** definitions and LUAI_DDEC for declarations). -** CHANGE them if you need to mark them in some special way. Elf/gcc -** (versions 3.2 and later) mark them as "hidden" to optimize access -** when Lua is compiled as a shared library. Not all elf targets support -** this attribute. Unfortunately, gcc does not offer a way to check -** whether the target offers that support, and those without support -** give a warning about it. To avoid these warnings, change to the -** default definition. -*/ -#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ - defined(__ELF__) /* { */ -#define LUAI_FUNC __attribute__((visibility("hidden"))) extern -#else /* }{ */ -#define LUAI_FUNC extern -#endif /* } */ - -#define LUAI_DDEC LUAI_FUNC -#define LUAI_DDEF /* empty */ - -/* }================================================================== */ - - -/* -** {================================================================== -** Compatibility with previous versions -** =================================================================== -*/ - -/* -@@ LUA_COMPAT_5_2 controls other macros for compatibility with Lua 5.2. -@@ LUA_COMPAT_5_1 controls other macros for compatibility with Lua 5.1. -** You can define it to get all options, or change specific options -** to fit your specific needs. -*/ -#if defined(LUA_COMPAT_5_2) /* { */ - -/* -@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated -** functions in the mathematical library. -*/ -#define LUA_COMPAT_MATHLIB - -/* -@@ LUA_COMPAT_BITLIB controls the presence of library 'bit32'. -*/ -#define LUA_COMPAT_BITLIB - -/* -@@ LUA_COMPAT_IPAIRS controls the effectiveness of the __ipairs metamethod. -*/ -#define LUA_COMPAT_IPAIRS - -/* -@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for -** manipulating other integer types (lua_pushunsigned, lua_tounsigned, -** luaL_checkint, luaL_checklong, etc.) -*/ -#define LUA_COMPAT_APIINTCASTS - -#endif /* } */ - - -#if defined(LUA_COMPAT_5_1) /* { */ - -/* Incompatibilities from 5.2 -> 5.3 */ -#define LUA_COMPAT_MATHLIB -#define LUA_COMPAT_APIINTCASTS - -/* -@@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'. -** You can replace it with 'table.unpack'. -*/ -#define LUA_COMPAT_UNPACK - -/* -@@ LUA_COMPAT_LOADERS controls the presence of table 'package.loaders'. -** You can replace it with 'package.searchers'. -*/ -#define LUA_COMPAT_LOADERS - -/* -@@ macro 'lua_cpcall' emulates deprecated function lua_cpcall. -** You can call your C function directly (with light C functions). -*/ -#define lua_cpcall(L,f,u) \ - (lua_pushcfunction(L, (f)), \ - lua_pushlightuserdata(L,(u)), \ - lua_pcall(L,1,0,0)) - - -/* -@@ LUA_COMPAT_LOG10 defines the function 'log10' in the math library. -** You can rewrite 'log10(x)' as 'log(x, 10)'. -*/ -#define LUA_COMPAT_LOG10 - -/* -@@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base -** library. You can rewrite 'loadstring(s)' as 'load(s)'. -*/ -#define LUA_COMPAT_LOADSTRING - -/* -@@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library. -*/ -#define LUA_COMPAT_MAXN - -/* -@@ The following macros supply trivial compatibility for some -** changes in the API. The macros themselves document how to -** change your code to avoid using them. -*/ -#define lua_strlen(L,i) lua_rawlen(L, (i)) - -#define lua_objlen(L,i) lua_rawlen(L, (i)) - -#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) -#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) - -/* -@@ LUA_COMPAT_MODULE controls compatibility with previous -** module functions 'module' (Lua) and 'luaL_register' (C). -*/ -#define LUA_COMPAT_MODULE - -#endif /* } */ - - -/* -@@ LUA_COMPAT_FLOATSTRING makes Lua format integral floats without a -@@ a float mark ('.0'). -** This macro is not on by default even in compatibility mode, -** because this is not really an incompatibility. -*/ -/* #define LUA_COMPAT_FLOATSTRING */ - -/* }================================================================== */ - - - -/* -** {================================================================== -** Configuration for Numbers. -** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_* -** satisfy your needs. -** =================================================================== -*/ - -/* -@@ LUA_NUMBER is the floating-point type used by Lua. -@@ LUAI_UACNUMBER is the result of an 'usual argument conversion' -@@ over a floating number. -@@ l_mathlim(x) corrects limit name 'x' to the proper float type -** by prefixing it with one of FLT/DBL/LDBL. -@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats. -@@ LUA_NUMBER_FMT is the format for writing floats. -@@ lua_number2str converts a float to a string. -@@ l_mathop allows the addition of an 'l' or 'f' to all math operations. -@@ lua_str2number converts a decimal numeric string to a number. -*/ - -#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */ - -#define LUA_NUMBER float - -#define l_mathlim(n) (FLT_##n) - -#define LUAI_UACNUMBER double - -#define LUA_NUMBER_FRMLEN "" -#define LUA_NUMBER_FMT "%.7g" - -#define l_mathop(op) op##f - -#define lua_str2number(s,p) strtof((s), (p)) - - -#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */ - -#define LUA_NUMBER long double - -#define l_mathlim(n) (LDBL_##n) - -#define LUAI_UACNUMBER long double - -#define LUA_NUMBER_FRMLEN "L" -#define LUA_NUMBER_FMT "%.19Lg" - -#define l_mathop(op) op##l - -#define lua_str2number(s,p) strtold((s), (p)) - -#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */ - -#define LUA_NUMBER double - -#define l_mathlim(n) (DBL_##n) - -#define LUAI_UACNUMBER double - -#define LUA_NUMBER_FRMLEN "" -#define LUA_NUMBER_FMT "%.14g" - -#define l_mathop(op) op - -#define lua_str2number(s,p) strtod((s), (p)) - -#else /* }{ */ - -#error "numeric float type not defined" - -#endif /* } */ - - -#define l_floor(x) (l_mathop(floor)(x)) - -#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) - - -/* -@@ lua_numbertointeger converts a float number to an integer, or -** returns 0 if float is not within the range of a lua_Integer. -** (The range comparisons are tricky because of rounding. The tests -** here assume a two-complement representation, where MININTEGER always -** has an exact representation as a float; MAXINTEGER may not have one, -** and therefore its conversion to float may have an ill-defined value.) -*/ -#define lua_numbertointeger(n,p) \ - ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ - (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ - (*(p) = (LUA_INTEGER)(n), 1)) - - - -/* -@@ LUA_INTEGER is the integer type used by Lua. -** -@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER. -** -@@ LUAI_UACINT is the result of an 'usual argument conversion' -@@ over a lUA_INTEGER. -@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers. -@@ LUA_INTEGER_FMT is the format for writing integers. -@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER. -@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER. -@@ lua_integer2str converts an integer to a string. -*/ - - -/* The following definitions are good for most cases here */ - -#define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d" -#define lua_integer2str(s,n) sprintf((s), LUA_INTEGER_FMT, (n)) - -#define LUAI_UACINT LUA_INTEGER - -/* -** use LUAI_UACINT here to avoid problems with promotions (which -** can turn a comparison between unsigneds into a signed comparison) -*/ -#define LUA_UNSIGNED unsigned LUAI_UACINT - - -/* now the variable definitions */ - -#if LUA_INT_TYPE == LUA_INT_INT /* { int */ - -#define LUA_INTEGER int -#define LUA_INTEGER_FRMLEN "" - -#define LUA_MAXINTEGER INT_MAX -#define LUA_MININTEGER INT_MIN - -#elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */ - -#define LUA_INTEGER long -#define LUA_INTEGER_FRMLEN "l" - -#define LUA_MAXINTEGER LONG_MAX -#define LUA_MININTEGER LONG_MIN - -#elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */ - -#if defined(LLONG_MAX) /* { */ -/* use ISO C99 stuff */ - -#define LUA_INTEGER long long -#define LUA_INTEGER_FRMLEN "ll" - -#define LUA_MAXINTEGER LLONG_MAX -#define LUA_MININTEGER LLONG_MIN - -#elif defined(LUA_USE_WINDOWS) /* }{ */ -/* in Windows, can use specific Windows types */ - -#define LUA_INTEGER __int64 -#define LUA_INTEGER_FRMLEN "I64" - -#define LUA_MAXINTEGER _I64_MAX -#define LUA_MININTEGER _I64_MIN - -#else /* }{ */ - -#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ - or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" - -#endif /* } */ - -#else /* }{ */ - -#error "numeric integer type not defined" - -#endif /* } */ - -/* }================================================================== */ - - -/* -** {================================================================== -** Dependencies with C99 and other C details -** =================================================================== -*/ - -/* -@@ lua_strx2number converts an hexadecimal numeric string to a number. -** In C99, 'strtod' does that conversion. Otherwise, you can -** leave 'lua_strx2number' undefined and Lua will provide its own -** implementation. -*/ -#if !defined(LUA_USE_C89) -#define lua_strx2number(s,p) lua_str2number(s,p) -#endif - - -/* -@@ lua_number2strx converts a float to an hexadecimal numeric string. -** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that. -** Otherwise, you can leave 'lua_number2strx' undefined and Lua will -** provide its own implementation. -*/ -#if !defined(LUA_USE_C89) -#define lua_number2strx(L,b,f,n) sprintf(b,f,n) -#endif - - -/* -** 'strtof' and 'opf' variants for math functions are not valid in -** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the -** availability of these variants. ('math.h' is already included in -** all files that use these macros.) -*/ -#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF)) -#undef l_mathop /* variants not available */ -#undef lua_str2number -#define l_mathop(op) (lua_Number)op /* no variant */ -#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) -#endif - - -/* -@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation -** functions. It must be a numerical type; Lua will use 'intptr_t' if -** available, otherwise it will use 'ptrdiff_t' (the nearest thing to -** 'intptr_t' in C89) -*/ -#define LUA_KCONTEXT ptrdiff_t - -#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ - __STDC_VERSION__ >= 199901L -#include -#if defined(INTPTR_MAX) /* even in C99 this type is optional */ -#undef LUA_KCONTEXT -#define LUA_KCONTEXT intptr_t -#endif -#endif - - -/* -@@ lua_getlocaledecpoint gets the locale "radix character" (decimal point). -** Change that if you do not want to use C locales. (Code using this -** macro must include header 'locale.h'.) -*/ -#if !defined(lua_getlocaledecpoint) -#define lua_getlocaledecpoint() (localeconv()->decimal_point[0]) -#endif - -/* }================================================================== */ - - -/* -** {================================================================== -** Language Variations -** ===================================================================== -*/ - -/* -@@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some -** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from -** numbers to strings. Define LUA_NOCVTS2N to turn off automatic -** coercion from strings to numbers. -*/ -/* #define LUA_NOCVTN2S */ -/* #define LUA_NOCVTS2N */ - - -/* -@@ LUA_USE_APICHECK turns on several consistency checks on the C API. -** Define it as a help when debugging C code. -*/ -#if defined(LUA_USE_APICHECK) -#include -#define luai_apicheck(l,e) assert(e) -#endif - -/* }================================================================== */ - - -/* -** {================================================================== -** Macros that affect the API and must be stable (that is, must be the -** same when you compile Lua and when you compile code that links to -** Lua). You probably do not want/need to change them. -** ===================================================================== -*/ - -/* -@@ LUAI_MAXSTACK limits the size of the Lua stack. -** CHANGE it if you need a different limit. This limit is arbitrary; -** its only purpose is to stop Lua from consuming unlimited stack -** space (and to reserve some numbers for pseudo-indices). -*/ -#if LUAI_BITSINT >= 32 -#define LUAI_MAXSTACK 1000000 -#else -#define LUAI_MAXSTACK 15000 -#endif - - -/* -@@ 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. -*/ -#define LUA_EXTRASPACE (sizeof(void *)) - - -/* -@@ LUA_IDSIZE gives the maximum size for the description of the source -@@ of a function in debug information. -** CHANGE it if you want a different size. -*/ -#define LUA_IDSIZE 60 - - -/* -@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. -** CHANGE it if it uses too much C-stack space. (For long double, -** 'string.format("%.99f", 1e4932)' needs ~5030 bytes, so a -** smaller buffer would force a memory allocation for each call to -** 'string.format'.) -*/ -#if defined(LUA_FLOAT_LONGDOUBLE) -#define LUAL_BUFFERSIZE 8192 -#else -#define LUAL_BUFFERSIZE ((int)(0x80 * sizeof(void*) * sizeof(lua_Integer))) -#endif - -/* }================================================================== */ - - -/* -@@ LUA_QL describes how error messages quote program elements. -** Lua does not use these macros anymore; they are here for -** compatibility only. -*/ -#define LUA_QL(x) "'" x "'" -#define LUA_QS LUA_QL("%s") - - - - -/* =================================================================== */ - -/* -** Local configuration. You can use this space to add your redefinitions -** without modifying the main part of the file. -*/ - - - - - -#endif - diff --git a/lua/lua53/lualib.h b/lua/lua53/lualib.h deleted file mode 100644 index 5165c0f..0000000 --- a/lua/lua53/lualib.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -** $Id: lualib.h,v 1.44 2014/02/06 17:32:33 roberto Exp $ -** Lua standard libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lualib_h -#define lualib_h - -#include "lua.h" - - - -LUAMOD_API int (luaopen_base) (lua_State *L); - -#define LUA_COLIBNAME "coroutine" -LUAMOD_API int (luaopen_coroutine) (lua_State *L); - -#define LUA_TABLIBNAME "table" -LUAMOD_API int (luaopen_table) (lua_State *L); - -#define LUA_IOLIBNAME "io" -LUAMOD_API int (luaopen_io) (lua_State *L); - -#define LUA_OSLIBNAME "os" -LUAMOD_API int (luaopen_os) (lua_State *L); - -#define LUA_STRLIBNAME "string" -LUAMOD_API int (luaopen_string) (lua_State *L); - -#define LUA_UTF8LIBNAME "utf8" -LUAMOD_API int (luaopen_utf8) (lua_State *L); - -#define LUA_BITLIBNAME "bit32" -LUAMOD_API int (luaopen_bit32) (lua_State *L); - -#define LUA_MATHLIBNAME "math" -LUAMOD_API int (luaopen_math) (lua_State *L); - -#define LUA_DBLIBNAME "debug" -LUAMOD_API int (luaopen_debug) (lua_State *L); - -#define LUA_LOADLIBNAME "package" -LUAMOD_API int (luaopen_package) (lua_State *L); - - -/* open all previous libraries */ -LUALIB_API void (luaL_openlibs) (lua_State *L); - - - -#if !defined(lua_assert) -#define lua_assert(x) ((void)0) -#endif - - -#endif diff --git a/lua/lua54/dummy.go b/lua/lua54/dummy.go deleted file mode 100644 index 651a797..0000000 --- a/lua/lua54/dummy.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build dummy - -// Package lua contains only a C header files. -// -// This Go file is part of a workaround for `go mod vendor`. -// Please see the file dummy.go in the parent directory for more information. -package lua diff --git a/lua/lua54/lauxlib.h b/lua/lua54/lauxlib.h deleted file mode 100644 index 59fef6a..0000000 --- a/lua/lua54/lauxlib.h +++ /dev/null @@ -1,276 +0,0 @@ -/* -** $Id: lauxlib.h $ -** Auxiliary functions for building Lua libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lauxlib_h -#define lauxlib_h - - -#include -#include - -#include "lua.h" - - -/* global table */ -#define LUA_GNAME "_G" - - -typedef struct luaL_Buffer luaL_Buffer; - - -/* extra error code for 'luaL_loadfilex' */ -#define LUA_ERRFILE (LUA_ERRERR+1) - - -/* key, in the registry, for table of loaded modules */ -#define LUA_LOADED_TABLE "_LOADED" - - -/* key, in the registry, for table of preloaded loaders */ -#define LUA_PRELOAD_TABLE "_PRELOAD" - - -typedef struct luaL_Reg { - const char *name; - lua_CFunction func; -} luaL_Reg; - - -#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number)) - -LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz); -#define luaL_checkversion(L) \ - luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES) - -LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); -LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len); -LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg); -LUALIB_API int (luaL_typeerror) (lua_State *L, int arg, const char *tname); -LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg, - size_t *l); -LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg, - const char *def, size_t *l); -LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg); -LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def); - -LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg); -LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg, - lua_Integer def); - -LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); -LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t); -LUALIB_API void (luaL_checkany) (lua_State *L, int arg); - -LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); -LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); -LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); -LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); - -LUALIB_API void (luaL_where) (lua_State *L, int lvl); -LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); - -LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def, - const char *const lst[]); - -LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname); -LUALIB_API int (luaL_execresult) (lua_State *L, int stat); - - -/* predefined references */ -#define LUA_NOREF (-2) -#define LUA_REFNIL (-1) - -LUALIB_API int (luaL_ref) (lua_State *L, int t); -LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); - -LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, - const char *mode); - -#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) - -LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, - const char *name, const char *mode); -LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); - -LUALIB_API lua_State *(luaL_newstate) (void); - -LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx); - -LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s, - const char *p, const char *r); -LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, - const char *p, const char *r); - -LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); - -LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname); - -LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1, - const char *msg, int level); - -LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname, - lua_CFunction openf, int glb); - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - - -#define luaL_newlibtable(L,l) \ - lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) - -#define luaL_newlib(L,l) \ - (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) - -#define luaL_argcheck(L, cond,arg,extramsg) \ - ((void)((cond) || luaL_argerror(L, (arg), (extramsg)))) - -#define luaL_argexpected(L,cond,arg,tname) \ - ((void)((cond) || luaL_typeerror(L, (arg), (tname)))) - -#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) -#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) - -#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) - -#define luaL_dofile(L, fn) \ - (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_dostring(L, s) \ - (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) - -#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) - -#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) - - -/* push the value used to represent failure/error */ -#define luaL_pushfail(L) lua_pushnil(L) - - -/* -** {====================================================== -** Generic Buffer manipulation -** ======================================================= -*/ - -struct luaL_Buffer { - char *b; /* buffer address */ - size_t size; /* buffer size */ - size_t n; /* number of characters in buffer */ - lua_State *L; - union { - LUAI_MAXALIGN; /* ensure maximum alignment for buffer */ - char b[LUAL_BUFFERSIZE]; /* initial buffer */ - } init; -}; - - -#define luaL_bufflen(bf) ((bf)->n) -#define luaL_buffaddr(bf) ((bf)->b) - - -#define luaL_addchar(B,c) \ - ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \ - ((B)->b[(B)->n++] = (c))) - -#define luaL_addsize(B,s) ((B)->n += (s)) - -#define luaL_buffsub(B,s) ((B)->n -= (s)) - -LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); -LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz); -LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); -LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); -LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz); -LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz); - -#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) - -/* }====================================================== */ - - - -/* -** {====================================================== -** File handles for IO library -** ======================================================= -*/ - -/* -** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and -** initial structure 'luaL_Stream' (it may contain other fields -** after that initial structure). -*/ - -#define LUA_FILEHANDLE "FILE*" - - -typedef struct luaL_Stream { - FILE *f; /* stream (NULL for incompletely created streams) */ - lua_CFunction closef; /* to close stream (NULL for closed streams) */ -} luaL_Stream; - -/* }====================================================== */ - -/* -** {================================================================== -** "Abstraction Layer" for basic report of messages and errors -** =================================================================== -*/ - -/* print a string */ -#if !defined(lua_writestring) -#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) -#endif - -/* print a newline and flush the output */ -#if !defined(lua_writeline) -#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout)) -#endif - -/* print an error message */ -#if !defined(lua_writestringerror) -#define lua_writestringerror(s,p) \ - (fprintf(stderr, (s), (p)), fflush(stderr)) -#endif - -/* }================================================================== */ - - -/* -** {============================================================ -** Compatibility with deprecated conversions -** ============================================================= -*/ -#if defined(LUA_COMPAT_APIINTCASTS) - -#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a)) -#define luaL_optunsigned(L,a,d) \ - ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d))) - -#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) -#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) - -#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) -#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) - -#endif -/* }============================================================ */ - - - -#endif - - diff --git a/lua/lua54/lua.h b/lua/lua54/lua.h deleted file mode 100644 index 6e00bc1..0000000 --- a/lua/lua54/lua.h +++ /dev/null @@ -1,518 +0,0 @@ -/* -** $Id: lua.h $ -** Lua - A Scripting Language -** Lua.org, PUC-Rio, Brazil (http://www.lua.org) -** See Copyright Notice at the end of this file -*/ - - -#ifndef lua_h -#define lua_h - -#include -#include - - -#include "luaconf.h" - - -#define LUA_VERSION_MAJOR "5" -#define LUA_VERSION_MINOR "4" -#define LUA_VERSION_RELEASE "2" - -#define LUA_VERSION_NUM 504 -#define LUA_VERSION_RELEASE_NUM (LUA_VERSION_NUM * 100 + 0) - -#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR -#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE -#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2020 Lua.org, PUC-Rio" -#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" - - -/* mark for precompiled code ('Lua') */ -#define LUA_SIGNATURE "\x1bLua" - -/* option for multiple returns in 'lua_pcall' and 'lua_call' */ -#define LUA_MULTRET (-1) - - -/* -** Pseudo-indices -** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty -** space after that to help overflow detection) -*/ -#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000) -#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) - - -/* thread status */ -#define LUA_OK 0 -#define LUA_YIELD 1 -#define LUA_ERRRUN 2 -#define LUA_ERRSYNTAX 3 -#define LUA_ERRMEM 4 -#define LUA_ERRERR 5 - - -typedef struct lua_State lua_State; - - -/* -** basic types -*/ -#define LUA_TNONE (-1) - -#define LUA_TNIL 0 -#define LUA_TBOOLEAN 1 -#define LUA_TLIGHTUSERDATA 2 -#define LUA_TNUMBER 3 -#define LUA_TSTRING 4 -#define LUA_TTABLE 5 -#define LUA_TFUNCTION 6 -#define LUA_TUSERDATA 7 -#define LUA_TTHREAD 8 - -#define LUA_NUMTYPES 9 - - - -/* minimum Lua stack available to a C function */ -#define LUA_MINSTACK 20 - - -/* predefined values in the registry */ -#define LUA_RIDX_MAINTHREAD 1 -#define LUA_RIDX_GLOBALS 2 -#define LUA_RIDX_LAST LUA_RIDX_GLOBALS - - -/* type of numbers in Lua */ -typedef LUA_NUMBER lua_Number; - - -/* type for integer functions */ -typedef LUA_INTEGER lua_Integer; - -/* unsigned integer type */ -typedef LUA_UNSIGNED lua_Unsigned; - -/* type for continuation-function contexts */ -typedef LUA_KCONTEXT lua_KContext; - - -/* -** Type for C functions registered with Lua -*/ -typedef int (*lua_CFunction) (lua_State *L); - -/* -** Type for continuation functions -*/ -typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); - - -/* -** Type for functions that read/write blocks when loading/dumping Lua chunks -*/ -typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); - -typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud); - - -/* -** Type for memory-allocation functions -*/ -typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); - - -/* -** Type for warning functions -*/ -typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont); - - - - -/* -** generic extra include file -*/ -#if defined(LUA_USER_H) -#include LUA_USER_H -#endif - - -/* -** RCS ident string -*/ -extern const char lua_ident[]; - - -/* -** state manipulation -*/ -LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); -LUA_API void (lua_close) (lua_State *L); -LUA_API lua_State *(lua_newthread) (lua_State *L); -LUA_API int (lua_resetthread) (lua_State *L); - -LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); - - -LUA_API lua_Number (lua_version) (lua_State *L); - - -/* -** basic stack manipulation -*/ -LUA_API int (lua_absindex) (lua_State *L, int idx); -LUA_API int (lua_gettop) (lua_State *L); -LUA_API void (lua_settop) (lua_State *L, int idx); -LUA_API void (lua_pushvalue) (lua_State *L, int idx); -LUA_API void (lua_rotate) (lua_State *L, int idx, int n); -LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx); -LUA_API int (lua_checkstack) (lua_State *L, int n); - -LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); - - -/* -** access functions (stack -> C) -*/ - -LUA_API int (lua_isnumber) (lua_State *L, int idx); -LUA_API int (lua_isstring) (lua_State *L, int idx); -LUA_API int (lua_iscfunction) (lua_State *L, int idx); -LUA_API int (lua_isinteger) (lua_State *L, int idx); -LUA_API int (lua_isuserdata) (lua_State *L, int idx); -LUA_API int (lua_type) (lua_State *L, int idx); -LUA_API const char *(lua_typename) (lua_State *L, int tp); - -LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum); -LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum); -LUA_API int (lua_toboolean) (lua_State *L, int idx); -LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); -LUA_API lua_Unsigned (lua_rawlen) (lua_State *L, int idx); -LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); -LUA_API void *(lua_touserdata) (lua_State *L, int idx); -LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); -LUA_API const void *(lua_topointer) (lua_State *L, int idx); - - -/* -** Comparison and arithmetic functions -*/ - -#define LUA_OPADD 0 /* ORDER TM, ORDER OP */ -#define LUA_OPSUB 1 -#define LUA_OPMUL 2 -#define LUA_OPMOD 3 -#define LUA_OPPOW 4 -#define LUA_OPDIV 5 -#define LUA_OPIDIV 6 -#define LUA_OPBAND 7 -#define LUA_OPBOR 8 -#define LUA_OPBXOR 9 -#define LUA_OPSHL 10 -#define LUA_OPSHR 11 -#define LUA_OPUNM 12 -#define LUA_OPBNOT 13 - -LUA_API void (lua_arith) (lua_State *L, int op); - -#define LUA_OPEQ 0 -#define LUA_OPLT 1 -#define LUA_OPLE 2 - -LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op); - - -/* -** push functions (C -> stack) -*/ -LUA_API void (lua_pushnil) (lua_State *L); -LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); -LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); -LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len); -LUA_API const char *(lua_pushstring) (lua_State *L, const char *s); -LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, - va_list argp); -LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); -LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); -LUA_API void (lua_pushboolean) (lua_State *L, int b); -LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); -LUA_API int (lua_pushthread) (lua_State *L); - - -/* -** get functions (Lua -> stack) -*/ -LUA_API int (lua_getglobal) (lua_State *L, const char *name); -LUA_API int (lua_gettable) (lua_State *L, int idx); -LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k); -LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n); -LUA_API int (lua_rawget) (lua_State *L, int idx); -LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n); -LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p); - -LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); -LUA_API void *(lua_newuserdatauv) (lua_State *L, size_t sz, int nuvalue); -LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); -LUA_API int (lua_getmetatable) (lua_State *L, int objindex); -LUA_API int (lua_getiuservalue) (lua_State *L, int idx, int n); - - -/* -** set functions (stack -> Lua) -*/ -LUA_API void (lua_setglobal) (lua_State *L, const char *name); -LUA_API void (lua_settable) (lua_State *L, int idx); -LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_seti) (lua_State *L, int idx, lua_Integer n); -LUA_API void (lua_rawset) (lua_State *L, int idx); -LUA_API void (lua_rawseti) (lua_State *L, int idx, lua_Integer n); -LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p); -LUA_API int (lua_setmetatable) (lua_State *L, int objindex); -LUA_API int (lua_setiuservalue) (lua_State *L, int idx, int n); - - -/* -** 'load' and 'call' functions (load and run Lua code) -*/ -LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults, - lua_KContext ctx, lua_KFunction k); -#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) - -LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc, - lua_KContext ctx, lua_KFunction k); -#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) - -LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname, const char *mode); - -LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip); - - -/* -** coroutine functions -*/ -LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx, - lua_KFunction k); -LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg, - int *nres); -LUA_API int (lua_status) (lua_State *L); -LUA_API int (lua_isyieldable) (lua_State *L); - -#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) - - -/* -** Warning-related functions -*/ -LUA_API void (lua_setwarnf) (lua_State *L, lua_WarnFunction f, void *ud); -LUA_API void (lua_warning) (lua_State *L, const char *msg, int tocont); - - -/* -** garbage-collection function and options -*/ - -#define LUA_GCSTOP 0 -#define LUA_GCRESTART 1 -#define LUA_GCCOLLECT 2 -#define LUA_GCCOUNT 3 -#define LUA_GCCOUNTB 4 -#define LUA_GCSTEP 5 -#define LUA_GCSETPAUSE 6 -#define LUA_GCSETSTEPMUL 7 -#define LUA_GCISRUNNING 9 -#define LUA_GCGEN 10 -#define LUA_GCINC 11 - -LUA_API int (lua_gc) (lua_State *L, int what, ...); -LUA_API int (lua_gc_compat) (lua_State *L, int what, int data); - - -/* -** miscellaneous functions -*/ - -LUA_API int (lua_error) (lua_State *L); - -LUA_API int (lua_next) (lua_State *L, int idx); - -LUA_API void (lua_concat) (lua_State *L, int n); -LUA_API void (lua_len) (lua_State *L, int idx); - -LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s); - -LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); -LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud); - -LUA_API void (lua_toclose) (lua_State *L, int idx); - - -/* -** {============================================================== -** some useful macros -** =============================================================== -*/ - -#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE)) - -#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL) -#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL) - -#define lua_pop(L,n) lua_settop(L, -(n)-1) - -#define lua_newtable(L) lua_createtable(L, 0, 0) - -#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) - -#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) - -#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) -#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) -#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) -#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) -#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) -#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) -#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) -#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) - -#define lua_pushliteral(L, s) lua_pushstring(L, "" s) - -#define lua_pushglobaltable(L) \ - ((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS)) - -#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) - - -#define lua_insert(L,idx) lua_rotate(L, (idx), 1) - -#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1)) - -#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1)) - -/* }============================================================== */ - - -/* -** {============================================================== -** compatibility macros -** =============================================================== -*/ -#if defined(LUA_COMPAT_APIINTCASTS) - -#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) -#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is)) -#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL) - -#endif - -#define lua_getuservalue(L,idx) lua_getiuservalue(L,idx,1) -#define lua_setuservalue(L,idx) lua_setiuservalue(L,idx,1) - -#define LUA_NUMTAGS LUA_NUMTYPES - -/* }============================================================== */ - -/* -** {====================================================================== -** Debug API -** ======================================================================= -*/ - - -/* -** Event codes -*/ -#define LUA_HOOKCALL 0 -#define LUA_HOOKRET 1 -#define LUA_HOOKLINE 2 -#define LUA_HOOKCOUNT 3 -#define LUA_HOOKTAILCALL 4 - - -/* -** Event masks -*/ -#define LUA_MASKCALL (1 << LUA_HOOKCALL) -#define LUA_MASKRET (1 << LUA_HOOKRET) -#define LUA_MASKLINE (1 << LUA_HOOKLINE) -#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) - -typedef struct lua_Debug lua_Debug; /* activation record */ - - -/* Functions to be called by the debugger in specific events */ -typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); - - -LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar); -LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar); -LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n); -LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n); - -LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n); -LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1, - int fidx2, int n2); - -LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count); -LUA_API lua_Hook (lua_gethook) (lua_State *L); -LUA_API int (lua_gethookmask) (lua_State *L); -LUA_API int (lua_gethookcount) (lua_State *L); - -LUA_API int (lua_setcstacklimit) (lua_State *L, unsigned int limit); - -struct lua_Debug { - int event; - const char *name; /* (n) */ - const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */ - const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */ - const char *source; /* (S) */ - size_t srclen; /* (S) */ - int currentline; /* (l) */ - int linedefined; /* (S) */ - int lastlinedefined; /* (S) */ - unsigned char nups; /* (u) number of upvalues */ - unsigned char nparams;/* (u) number of parameters */ - char isvararg; /* (u) */ - char istailcall; /* (t) */ - unsigned short ftransfer; /* (r) index of first value transferred */ - unsigned short ntransfer; /* (r) number of transferred values */ - char short_src[LUA_IDSIZE]; /* (S) */ - /* private part */ - struct CallInfo *i_ci; /* active function */ -}; - -/* }====================================================================== */ - - -/****************************************************************************** -* Copyright (C) 1994-2020 Lua.org, PUC-Rio. -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ - - -#endif diff --git a/lua/lua54/luaconf.h b/lua/lua54/luaconf.h deleted file mode 100644 index d9cf18c..0000000 --- a/lua/lua54/luaconf.h +++ /dev/null @@ -1,761 +0,0 @@ -/* -** $Id: luaconf.h $ -** Configuration file for Lua -** See Copyright Notice in lua.h -*/ - - -#ifndef luaconf_h -#define luaconf_h - -#include -#include - - -/* -** =================================================================== -** General Configuration File for Lua -** -** Some definitions here can be changed externally, through the -** compiler (e.g., with '-D' options). Those are protected by -** '#if !defined' guards. However, several other definitions should -** be changed directly here, either because they affect the Lua -** ABI (by making the changes here, you ensure that all software -** connected to Lua, such as C libraries, will be compiled with the -** same configuration); or because they are seldom changed. -** -** Search for "@@" to find all configurable definitions. -** =================================================================== -*/ - - -/* -** {==================================================================== -** System Configuration: macros to adapt (if needed) Lua to some -** particular platform, for instance restricting it to C89. -** ===================================================================== -*/ - -/* -@@ LUA_USE_C89 controls the use of non-ISO-C89 features. -** Define it if you want Lua to avoid the use of a few C99 features -** or Windows-specific features on Windows. -*/ -/* #define LUA_USE_C89 */ - - -/* -** By default, Lua on Windows use (some) specific Windows features -*/ -#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE) -#define LUA_USE_WINDOWS /* enable goodies for regular Windows */ -#endif - - -#if defined(LUA_USE_WINDOWS) -#define LUA_DL_DLL /* enable support for DLL */ -#define LUA_USE_C89 /* broadly, Windows is C89 */ -#endif - - -#if defined(LUA_USE_LINUX) -#define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ -#endif - - -#if defined(LUA_USE_MACOSX) -#define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* MacOS does not need -ldl */ -#endif - - -/* -@@ LUAI_IS32INT is true iff 'int' has (at least) 32 bits. -*/ -#define LUAI_IS32INT ((UINT_MAX >> 30) >= 3) - -/* }================================================================== */ - - - -/* -** {================================================================== -** Configuration for Number types. -** =================================================================== -*/ - -/* -@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. -*/ -/* #define LUA_32BITS */ - - -/* -@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for -** C89 ('long' and 'double'); Windows always has '__int64', so it does -** not need to use this case. -*/ -#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS) -#define LUA_C89_NUMBERS -#endif - - -/* -@@ LUA_INT_TYPE defines the type for Lua integers. -@@ LUA_FLOAT_TYPE defines the type for Lua floats. -** Lua should work fine with any mix of these options supported -** by your C compiler. The usual configurations are 64-bit integers -** and 'double' (the default), 32-bit integers and 'float' (for -** restricted platforms), and 'long'/'double' (for C compilers not -** compliant with C99, which may not have support for 'long long'). -*/ - -/* predefined options for LUA_INT_TYPE */ -#define LUA_INT_INT 1 -#define LUA_INT_LONG 2 -#define LUA_INT_LONGLONG 3 - -/* predefined options for LUA_FLOAT_TYPE */ -#define LUA_FLOAT_FLOAT 1 -#define LUA_FLOAT_DOUBLE 2 -#define LUA_FLOAT_LONGDOUBLE 3 - -#if defined(LUA_32BITS) /* { */ -/* -** 32-bit integers and 'float' -*/ -#if LUAI_IS32INT /* use 'int' if big enough */ -#define LUA_INT_TYPE LUA_INT_INT -#else /* otherwise use 'long' */ -#define LUA_INT_TYPE LUA_INT_LONG -#endif -#define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT - -#elif defined(LUA_C89_NUMBERS) /* }{ */ -/* -** largest types available for C89 ('long' and 'double') -*/ -#define LUA_INT_TYPE LUA_INT_LONG -#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE - -#endif /* } */ - - -/* -** default configuration for 64-bit Lua ('long long' and 'double') -*/ -#if !defined(LUA_INT_TYPE) -#define LUA_INT_TYPE LUA_INT_LONGLONG -#endif - -#if !defined(LUA_FLOAT_TYPE) -#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE -#endif - -/* }================================================================== */ - - - -/* -** {================================================================== -** Configuration for Paths. -** =================================================================== -*/ - -/* -** LUA_PATH_SEP is the character that separates templates in a path. -** LUA_PATH_MARK is the string that marks the substitution points in a -** template. -** LUA_EXEC_DIR in a Windows path is replaced by the executable's -** directory. -*/ -#define LUA_PATH_SEP ";" -#define LUA_PATH_MARK "?" -#define LUA_EXEC_DIR "!" - - -/* -@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for -** Lua libraries. -@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for -** C libraries. -** CHANGE them if your machine has a non-conventional directory -** hierarchy or if you want to install your libraries in -** non-conventional directories. -*/ - -#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR -#if defined(_WIN32) /* { */ -/* -** In Windows, any exclamation mark ('!') in the path is replaced by the -** path of the directory of the executable file of the current process. -*/ -#define LUA_LDIR "!\\lua\\" -#define LUA_CDIR "!\\" -#define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\" - -#if !defined(LUA_PATH_DEFAULT) -#define LUA_PATH_DEFAULT \ - LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \ - LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ - ".\\?.lua;" ".\\?\\init.lua" -#endif - -#if !defined(LUA_CPATH_DEFAULT) -#define LUA_CPATH_DEFAULT \ - LUA_CDIR"?.dll;" \ - LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \ - LUA_CDIR"loadall.dll;" ".\\?.dll" -#endif - -#else /* }{ */ - -#define LUA_ROOT "/usr/local/" -#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/" -#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/" - -#if !defined(LUA_PATH_DEFAULT) -#define LUA_PATH_DEFAULT \ - LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \ - "./?.lua;" "./?/init.lua" -#endif - -#if !defined(LUA_CPATH_DEFAULT) -#define LUA_CPATH_DEFAULT \ - LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" -#endif - -#endif /* } */ - - -/* -@@ LUA_DIRSEP is the directory separator (for submodules). -** CHANGE it if your machine does not use "/" as the directory separator -** and is not Windows. (On Windows Lua automatically uses "\".) -*/ -#if !defined(LUA_DIRSEP) - -#if defined(_WIN32) -#define LUA_DIRSEP "\\" -#else -#define LUA_DIRSEP "/" -#endif - -#endif - -/* }================================================================== */ - - -/* -** {================================================================== -** Marks for exported symbols in the C code -** =================================================================== -*/ - -/* -@@ LUA_API is a mark for all core API functions. -@@ LUALIB_API is a mark for all auxiliary library functions. -@@ LUAMOD_API is a mark for all standard library opening functions. -** CHANGE them if you need to define those functions in some special way. -** For instance, if you want to create one Windows DLL with the core and -** the libraries, you may want to use the following definition (define -** LUA_BUILD_AS_DLL to get it). -*/ -#if defined(LUA_BUILD_AS_DLL) /* { */ - -#if defined(LUA_CORE) || defined(LUA_LIB) /* { */ -#define LUA_API __declspec(dllexport) -#else /* }{ */ -#define LUA_API __declspec(dllimport) -#endif /* } */ - -#else /* }{ */ - -#define LUA_API extern - -#endif /* } */ - - -/* -** More often than not the libs go together with the core. -*/ -#define LUALIB_API LUA_API -#define LUAMOD_API LUA_API - - -/* -@@ LUAI_FUNC is a mark for all extern functions that are not to be -** exported to outside modules. -@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables, -** none of which to be exported to outside modules (LUAI_DDEF for -** definitions and LUAI_DDEC for declarations). -** CHANGE them if you need to mark them in some special way. Elf/gcc -** (versions 3.2 and later) mark them as "hidden" to optimize access -** when Lua is compiled as a shared library. Not all elf targets support -** this attribute. Unfortunately, gcc does not offer a way to check -** whether the target offers that support, and those without support -** give a warning about it. To avoid these warnings, change to the -** default definition. -*/ -#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ - defined(__ELF__) /* { */ -#define LUAI_FUNC __attribute__((visibility("internal"))) extern -#else /* }{ */ -#define LUAI_FUNC extern -#endif /* } */ - -#define LUAI_DDEC(dec) LUAI_FUNC dec -#define LUAI_DDEF /* empty */ - -/* }================================================================== */ - - -/* -** {================================================================== -** Compatibility with previous versions -** =================================================================== -*/ - -/* -@@ LUA_COMPAT_5_3 controls other macros for compatibility with Lua 5.3. -** You can define it to get all options, or change specific options -** to fit your specific needs. -*/ -#if defined(LUA_COMPAT_5_3) /* { */ - -/* -@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated -** functions in the mathematical library. -** (These functions were already officially removed in 5.3; -** nevertheless they are still available here.) -*/ -#define LUA_COMPAT_MATHLIB - -/* -@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for -** manipulating other integer types (lua_pushunsigned, lua_tounsigned, -** luaL_checkint, luaL_checklong, etc.) -** (These macros were also officially removed in 5.3, but they are still -** available here.) -*/ -#define LUA_COMPAT_APIINTCASTS - - -/* -@@ LUA_COMPAT_LT_LE controls the emulation of the '__le' metamethod -** using '__lt'. -*/ -#define LUA_COMPAT_LT_LE - - -/* -@@ The following macros supply trivial compatibility for some -** changes in the API. The macros themselves document how to -** change your code to avoid using them. -** (Once more, these macros were officially removed in 5.3, but they are -** still available here.) -*/ -#define lua_strlen(L,i) lua_rawlen(L, (i)) - -#define lua_objlen(L,i) lua_rawlen(L, (i)) - -#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) -#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) - -#endif /* } */ - -/* }================================================================== */ - - - -/* -** {================================================================== -** Configuration for Numbers. -** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_* -** satisfy your needs. -** =================================================================== -*/ - -/* -@@ LUA_NUMBER is the floating-point type used by Lua. -@@ LUAI_UACNUMBER is the result of a 'default argument promotion' -@@ over a floating number. -@@ l_floatatt(x) corrects float attribute 'x' to the proper float type -** by prefixing it with one of FLT/DBL/LDBL. -@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats. -@@ LUA_NUMBER_FMT is the format for writing floats. -@@ lua_number2str converts a float to a string. -@@ l_mathop allows the addition of an 'l' or 'f' to all math operations. -@@ l_floor takes the floor of a float. -@@ lua_str2number converts a decimal numeral to a number. -*/ - - -/* The following definitions are good for most cases here */ - -#define l_floor(x) (l_mathop(floor)(x)) - -#define lua_number2str(s,sz,n) \ - l_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n)) - -/* -@@ lua_numbertointeger converts a float number with an integral value -** to an integer, or returns 0 if float is not within the range of -** a lua_Integer. (The range comparisons are tricky because of -** rounding. The tests here assume a two-complement representation, -** where MININTEGER always has an exact representation as a float; -** MAXINTEGER may not have one, and therefore its conversion to float -** may have an ill-defined value.) -*/ -#define lua_numbertointeger(n,p) \ - ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ - (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ - (*(p) = (LUA_INTEGER)(n), 1)) - - -/* now the variable definitions */ - -#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */ - -#define LUA_NUMBER float - -#define l_floatatt(n) (FLT_##n) - -#define LUAI_UACNUMBER double - -#define LUA_NUMBER_FRMLEN "" -#define LUA_NUMBER_FMT "%.7g" - -#define l_mathop(op) op##f - -#define lua_str2number(s,p) strtof((s), (p)) - - -#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */ - -#define LUA_NUMBER long double - -#define l_floatatt(n) (LDBL_##n) - -#define LUAI_UACNUMBER long double - -#define LUA_NUMBER_FRMLEN "L" -#define LUA_NUMBER_FMT "%.19Lg" - -#define l_mathop(op) op##l - -#define lua_str2number(s,p) strtold((s), (p)) - -#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */ - -#define LUA_NUMBER double - -#define l_floatatt(n) (DBL_##n) - -#define LUAI_UACNUMBER double - -#define LUA_NUMBER_FRMLEN "" -#define LUA_NUMBER_FMT "%.14g" - -#define l_mathop(op) op - -#define lua_str2number(s,p) strtod((s), (p)) - -#else /* }{ */ - -#error "numeric float type not defined" - -#endif /* } */ - - - -/* -@@ LUA_INTEGER is the integer type used by Lua. -** -@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER. -** -@@ LUAI_UACINT is the result of a 'default argument promotion' -@@ over a LUA_INTEGER. -@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers. -@@ LUA_INTEGER_FMT is the format for writing integers. -@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER. -@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER. -@@ LUA_MAXUNSIGNED is the maximum value for a LUA_UNSIGNED. -@@ LUA_UNSIGNEDBITS is the number of bits in a LUA_UNSIGNED. -@@ lua_integer2str converts an integer to a string. -*/ - - -/* The following definitions are good for most cases here */ - -#define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d" - -#define LUAI_UACINT LUA_INTEGER - -#define lua_integer2str(s,sz,n) \ - l_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n)) - -/* -** use LUAI_UACINT here to avoid problems with promotions (which -** can turn a comparison between unsigneds into a signed comparison) -*/ -#define LUA_UNSIGNED unsigned LUAI_UACINT - - -#define LUA_UNSIGNEDBITS (sizeof(LUA_UNSIGNED) * CHAR_BIT) - - -/* now the variable definitions */ - -#if LUA_INT_TYPE == LUA_INT_INT /* { int */ - -#define LUA_INTEGER int -#define LUA_INTEGER_FRMLEN "" - -#define LUA_MAXINTEGER INT_MAX -#define LUA_MININTEGER INT_MIN - -#define LUA_MAXUNSIGNED UINT_MAX - -#elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */ - -#define LUA_INTEGER long -#define LUA_INTEGER_FRMLEN "l" - -#define LUA_MAXINTEGER LONG_MAX -#define LUA_MININTEGER LONG_MIN - -#define LUA_MAXUNSIGNED ULONG_MAX - -#elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */ - -/* use presence of macro LLONG_MAX as proxy for C99 compliance */ -#if defined(LLONG_MAX) /* { */ -/* use ISO C99 stuff */ - -#define LUA_INTEGER long long -#define LUA_INTEGER_FRMLEN "ll" - -#define LUA_MAXINTEGER LLONG_MAX -#define LUA_MININTEGER LLONG_MIN - -#define LUA_MAXUNSIGNED ULLONG_MAX - -#elif defined(LUA_USE_WINDOWS) /* }{ */ -/* in Windows, can use specific Windows types */ - -#define LUA_INTEGER __int64 -#define LUA_INTEGER_FRMLEN "I64" - -#define LUA_MAXINTEGER _I64_MAX -#define LUA_MININTEGER _I64_MIN - -#define LUA_MAXUNSIGNED _UI64_MAX - -#else /* }{ */ - -#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ - or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" - -#endif /* } */ - -#else /* }{ */ - -#error "numeric integer type not defined" - -#endif /* } */ - -/* }================================================================== */ - - -/* -** {================================================================== -** Dependencies with C99 and other C details -** =================================================================== -*/ - -/* -@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89. -** (All uses in Lua have only one format item.) -*/ -#if !defined(LUA_USE_C89) -#define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i) -#else -#define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i)) -#endif - - -/* -@@ lua_strx2number converts a hexadecimal numeral to a number. -** In C99, 'strtod' does that conversion. Otherwise, you can -** leave 'lua_strx2number' undefined and Lua will provide its own -** implementation. -*/ -#if !defined(LUA_USE_C89) -#define lua_strx2number(s,p) lua_str2number(s,p) -#endif - - -/* -@@ lua_pointer2str converts a pointer to a readable string in a -** non-specified way. -*/ -#define lua_pointer2str(buff,sz,p) l_sprintf(buff,sz,"%p",p) - - -/* -@@ lua_number2strx converts a float to a hexadecimal numeral. -** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that. -** Otherwise, you can leave 'lua_number2strx' undefined and Lua will -** provide its own implementation. -*/ -#if !defined(LUA_USE_C89) -#define lua_number2strx(L,b,sz,f,n) \ - ((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n))) -#endif - - -/* -** 'strtof' and 'opf' variants for math functions are not valid in -** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the -** availability of these variants. ('math.h' is already included in -** all files that use these macros.) -*/ -#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF)) -#undef l_mathop /* variants not available */ -#undef lua_str2number -#define l_mathop(op) (lua_Number)op /* no variant */ -#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) -#endif - - -/* -@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation -** functions. It must be a numerical type; Lua will use 'intptr_t' if -** available, otherwise it will use 'ptrdiff_t' (the nearest thing to -** 'intptr_t' in C89) -*/ -#define LUA_KCONTEXT ptrdiff_t - -#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ - __STDC_VERSION__ >= 199901L -#include -#if defined(INTPTR_MAX) /* even in C99 this type is optional */ -#undef LUA_KCONTEXT -#define LUA_KCONTEXT intptr_t -#endif -#endif - - -/* -@@ lua_getlocaledecpoint gets the locale "radix character" (decimal point). -** Change that if you do not want to use C locales. (Code using this -** macro must include the header 'locale.h'.) -*/ -#if !defined(lua_getlocaledecpoint) -#define lua_getlocaledecpoint() (localeconv()->decimal_point[0]) -#endif - -/* }================================================================== */ - - -/* -** {================================================================== -** Language Variations -** ===================================================================== -*/ - -/* -@@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some -** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from -** numbers to strings. Define LUA_NOCVTS2N to turn off automatic -** coercion from strings to numbers. -*/ -/* #define LUA_NOCVTN2S */ -/* #define LUA_NOCVTS2N */ - - -/* -@@ LUA_USE_APICHECK turns on several consistency checks on the C API. -** Define it as a help when debugging C code. -*/ -#if defined(LUA_USE_APICHECK) -#include -#define luai_apicheck(l,e) assert(e) -#endif - -/* }================================================================== */ - - -/* -** {================================================================== -** Macros that affect the API and must be stable (that is, must be the -** same when you compile Lua and when you compile code that links to -** Lua). -** ===================================================================== -*/ - -/* -@@ LUAI_MAXSTACK limits the size of the Lua stack. -** CHANGE it if you need a different limit. This limit is arbitrary; -** its only purpose is to stop Lua from consuming unlimited stack -** space (and to reserve some numbers for pseudo-indices). -** (It must fit into max(size_t)/32.) -*/ -#if LUAI_IS32INT -#define LUAI_MAXSTACK 1000000 -#else -#define LUAI_MAXSTACK 15000 -#endif - - -/* -@@ 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. -*/ -#define LUA_EXTRASPACE (sizeof(void *)) - - -/* -@@ LUA_IDSIZE gives the maximum size for the description of the source -@@ of a function in debug information. -** CHANGE it if you want a different size. -*/ -#define LUA_IDSIZE 60 - - -/* -@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. -*/ -#define LUAL_BUFFERSIZE ((int)(16 * sizeof(void*) * sizeof(lua_Number))) - - -/* -@@ LUAI_MAXALIGN defines fields that, when used in a union, ensure -** maximum alignment for the other items in that union. -*/ -#define LUAI_MAXALIGN lua_Number n; double u; void *s; lua_Integer i; long l - -/* }================================================================== */ - - - - - -/* =================================================================== */ - -/* -** Local configuration. You can use this space to add your redefinitions -** without modifying the main part of the file. -*/ - - - - - -#endif - diff --git a/lua/lua54/lualib.h b/lua/lua54/lualib.h deleted file mode 100644 index eb08b53..0000000 --- a/lua/lua54/lualib.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -** $Id: lualib.h $ -** Lua standard libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lualib_h -#define lualib_h - -#include "lua.h" - - -/* version suffix for environment variable names */ -#define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR - - -LUAMOD_API int (luaopen_base) (lua_State *L); - -#define LUA_COLIBNAME "coroutine" -LUAMOD_API int (luaopen_coroutine) (lua_State *L); - -#define LUA_TABLIBNAME "table" -LUAMOD_API int (luaopen_table) (lua_State *L); - -#define LUA_IOLIBNAME "io" -LUAMOD_API int (luaopen_io) (lua_State *L); - -#define LUA_OSLIBNAME "os" -LUAMOD_API int (luaopen_os) (lua_State *L); - -#define LUA_STRLIBNAME "string" -LUAMOD_API int (luaopen_string) (lua_State *L); - -#define LUA_UTF8LIBNAME "utf8" -LUAMOD_API int (luaopen_utf8) (lua_State *L); - -#define LUA_MATHLIBNAME "math" -LUAMOD_API int (luaopen_math) (lua_State *L); - -#define LUA_DBLIBNAME "debug" -LUAMOD_API int (luaopen_debug) (lua_State *L); - -#define LUA_LOADLIBNAME "package" -LUAMOD_API int (luaopen_package) (lua_State *L); - - -/* open all previous libraries */ -LUALIB_API void (luaL_openlibs) (lua_State *L); - - - -#if !defined(lua_assert) -#define lua_assert(x) ((void)0) -#endif - - -#endif diff --git a/lua/lua_defs_lua51.go b/lua/lua_defs.go similarity index 95% rename from lua/lua_defs_lua51.go rename to lua/lua_defs.go index 3696c39..2109856 100644 --- a/lua/lua_defs_lua51.go +++ b/lua/lua_defs.go @@ -1,11 +1,9 @@ -//+build !lua52,!lua53,!lua54 - package lua /* -#include - #include - #include +#cgo CFLAGS: -I ${SRCDIR} -I ${SRCDIR}/lua + +#include "golua.h" */ import "C" diff --git a/lua/lua_defs_lua52.go b/lua/lua_defs_lua52.go deleted file mode 100644 index c6623f0..0000000 --- a/lua/lua_defs_lua52.go +++ /dev/null @@ -1,71 +0,0 @@ -//+build lua52 - -package lua - -/* -#include - #include - #include - -*/ -import "C" - -type LuaValType int - -const ( - LUA_TNIL = LuaValType(C.LUA_TNIL) - LUA_TNUMBER = LuaValType(C.LUA_TNUMBER) - LUA_TBOOLEAN = LuaValType(C.LUA_TBOOLEAN) - LUA_TSTRING = LuaValType(C.LUA_TSTRING) - LUA_TTABLE = LuaValType(C.LUA_TTABLE) - LUA_TFUNCTION = LuaValType(C.LUA_TFUNCTION) - LUA_TUSERDATA = LuaValType(C.LUA_TUSERDATA) - LUA_TTHREAD = LuaValType(C.LUA_TTHREAD) - LUA_TLIGHTUSERDATA = LuaValType(C.LUA_TLIGHTUSERDATA) -) - -const ( - LUA_OK = C.LUA_OK - LUA_VERSION = C.LUA_VERSION - LUA_RELEASE = C.LUA_RELEASE - LUA_VERSION_NUM = C.LUA_VERSION_NUM - LUA_COPYRIGHT = C.LUA_COPYRIGHT - LUA_AUTHORS = C.LUA_AUTHORS - LUA_MULTRET = C.LUA_MULTRET - LUA_REGISTRYINDEX = C.LUA_REGISTRYINDEX - LUA_YIELD = C.LUA_YIELD - LUA_ERRRUN = C.LUA_ERRRUN - LUA_ERRSYNTAX = C.LUA_ERRSYNTAX - LUA_ERRMEM = C.LUA_ERRMEM - LUA_ERRERR = C.LUA_ERRERR - LUA_TNONE = C.LUA_TNONE - LUA_MINSTACK = C.LUA_MINSTACK - LUA_GCSTOP = C.LUA_GCSTOP - LUA_GCRESTART = C.LUA_GCRESTART - LUA_GCCOLLECT = C.LUA_GCCOLLECT - LUA_GCCOUNT = C.LUA_GCCOUNT - LUA_GCCOUNTB = C.LUA_GCCOUNTB - LUA_GCSTEP = C.LUA_GCSTEP - LUA_GCSETPAUSE = C.LUA_GCSETPAUSE - LUA_GCSETSTEPMUL = C.LUA_GCSETSTEPMUL - LUA_HOOKCALL = C.LUA_HOOKCALL - LUA_HOOKRET = C.LUA_HOOKRET - LUA_HOOKLINE = C.LUA_HOOKLINE - LUA_HOOKCOUNT = C.LUA_HOOKCOUNT - LUA_MASKCALL = C.LUA_MASKCALL - LUA_MASKRET = C.LUA_MASKRET - LUA_MASKLINE = C.LUA_MASKLINE - LUA_MASKCOUNT = C.LUA_MASKCOUNT - LUA_ERRFILE = C.LUA_ERRFILE - LUA_NOREF = C.LUA_NOREF - LUA_REFNIL = C.LUA_REFNIL - LUA_FILEHANDLE = C.LUA_FILEHANDLE - LUA_COLIBNAME = C.LUA_COLIBNAME - LUA_TABLIBNAME = C.LUA_TABLIBNAME - LUA_IOLIBNAME = C.LUA_IOLIBNAME - LUA_OSLIBNAME = C.LUA_OSLIBNAME - LUA_STRLIBNAME = C.LUA_STRLIBNAME - LUA_MATHLIBNAME = C.LUA_MATHLIBNAME - LUA_DBLIBNAME = C.LUA_DBLIBNAME - LUA_LOADLIBNAME = C.LUA_LOADLIBNAME -) diff --git a/lua/lua_defs_lua53.go b/lua/lua_defs_lua53.go deleted file mode 100644 index 0a67433..0000000 --- a/lua/lua_defs_lua53.go +++ /dev/null @@ -1,71 +0,0 @@ -//+build lua53 - -package lua - -/* -#include - #include - #include - -*/ -import "C" - -type LuaValType int - -const ( - LUA_TNIL = LuaValType(C.LUA_TNIL) - LUA_TNUMBER = LuaValType(C.LUA_TNUMBER) - LUA_TBOOLEAN = LuaValType(C.LUA_TBOOLEAN) - LUA_TSTRING = LuaValType(C.LUA_TSTRING) - LUA_TTABLE = LuaValType(C.LUA_TTABLE) - LUA_TFUNCTION = LuaValType(C.LUA_TFUNCTION) - LUA_TUSERDATA = LuaValType(C.LUA_TUSERDATA) - LUA_TTHREAD = LuaValType(C.LUA_TTHREAD) - LUA_TLIGHTUSERDATA = LuaValType(C.LUA_TLIGHTUSERDATA) -) - -const ( - LUA_OK = C.LUA_OK - LUA_VERSION = C.LUA_VERSION - LUA_RELEASE = C.LUA_RELEASE - LUA_VERSION_NUM = C.LUA_VERSION_NUM - LUA_COPYRIGHT = C.LUA_COPYRIGHT - LUA_AUTHORS = C.LUA_AUTHORS - LUA_MULTRET = C.LUA_MULTRET - LUA_REGISTRYINDEX = C.LUA_REGISTRYINDEX - LUA_YIELD = C.LUA_YIELD - LUA_ERRRUN = C.LUA_ERRRUN - LUA_ERRSYNTAX = C.LUA_ERRSYNTAX - LUA_ERRMEM = C.LUA_ERRMEM - LUA_ERRERR = C.LUA_ERRERR - LUA_TNONE = C.LUA_TNONE - LUA_MINSTACK = C.LUA_MINSTACK - LUA_GCSTOP = C.LUA_GCSTOP - LUA_GCRESTART = C.LUA_GCRESTART - LUA_GCCOLLECT = C.LUA_GCCOLLECT - LUA_GCCOUNT = C.LUA_GCCOUNT - LUA_GCCOUNTB = C.LUA_GCCOUNTB - LUA_GCSTEP = C.LUA_GCSTEP - LUA_GCSETPAUSE = C.LUA_GCSETPAUSE - LUA_GCSETSTEPMUL = C.LUA_GCSETSTEPMUL - LUA_HOOKCALL = C.LUA_HOOKCALL - LUA_HOOKRET = C.LUA_HOOKRET - LUA_HOOKLINE = C.LUA_HOOKLINE - LUA_HOOKCOUNT = C.LUA_HOOKCOUNT - LUA_MASKCALL = C.LUA_MASKCALL - LUA_MASKRET = C.LUA_MASKRET - LUA_MASKLINE = C.LUA_MASKLINE - LUA_MASKCOUNT = C.LUA_MASKCOUNT - LUA_ERRFILE = C.LUA_ERRFILE - LUA_NOREF = C.LUA_NOREF - LUA_REFNIL = C.LUA_REFNIL - LUA_FILEHANDLE = C.LUA_FILEHANDLE - LUA_COLIBNAME = C.LUA_COLIBNAME - LUA_TABLIBNAME = C.LUA_TABLIBNAME - LUA_IOLIBNAME = C.LUA_IOLIBNAME - LUA_OSLIBNAME = C.LUA_OSLIBNAME - LUA_STRLIBNAME = C.LUA_STRLIBNAME - LUA_MATHLIBNAME = C.LUA_MATHLIBNAME - LUA_DBLIBNAME = C.LUA_DBLIBNAME - LUA_LOADLIBNAME = C.LUA_LOADLIBNAME -) diff --git a/lua/lua_defs_lua54.go b/lua/lua_defs_lua54.go deleted file mode 100644 index f376835..0000000 --- a/lua/lua_defs_lua54.go +++ /dev/null @@ -1,71 +0,0 @@ -//+build lua54 - -package lua - -/* -#include - #include - #include - -*/ -import "C" - -type LuaValType int - -const ( - LUA_TNIL = LuaValType(C.LUA_TNIL) - LUA_TNUMBER = LuaValType(C.LUA_TNUMBER) - LUA_TBOOLEAN = LuaValType(C.LUA_TBOOLEAN) - LUA_TSTRING = LuaValType(C.LUA_TSTRING) - LUA_TTABLE = LuaValType(C.LUA_TTABLE) - LUA_TFUNCTION = LuaValType(C.LUA_TFUNCTION) - LUA_TUSERDATA = LuaValType(C.LUA_TUSERDATA) - LUA_TTHREAD = LuaValType(C.LUA_TTHREAD) - LUA_TLIGHTUSERDATA = LuaValType(C.LUA_TLIGHTUSERDATA) -) - -const ( - LUA_OK = C.LUA_OK - LUA_VERSION = C.LUA_VERSION - LUA_RELEASE = C.LUA_RELEASE - LUA_VERSION_NUM = C.LUA_VERSION_NUM - LUA_COPYRIGHT = C.LUA_COPYRIGHT - LUA_AUTHORS = C.LUA_AUTHORS - LUA_MULTRET = C.LUA_MULTRET - LUA_REGISTRYINDEX = C.LUA_REGISTRYINDEX - LUA_YIELD = C.LUA_YIELD - LUA_ERRRUN = C.LUA_ERRRUN - LUA_ERRSYNTAX = C.LUA_ERRSYNTAX - LUA_ERRMEM = C.LUA_ERRMEM - LUA_ERRERR = C.LUA_ERRERR - LUA_TNONE = C.LUA_TNONE - LUA_MINSTACK = C.LUA_MINSTACK - LUA_GCSTOP = C.LUA_GCSTOP - LUA_GCRESTART = C.LUA_GCRESTART - LUA_GCCOLLECT = C.LUA_GCCOLLECT - LUA_GCCOUNT = C.LUA_GCCOUNT - LUA_GCCOUNTB = C.LUA_GCCOUNTB - LUA_GCSTEP = C.LUA_GCSTEP - LUA_GCSETPAUSE = C.LUA_GCSETPAUSE - LUA_GCSETSTEPMUL = C.LUA_GCSETSTEPMUL - LUA_HOOKCALL = C.LUA_HOOKCALL - LUA_HOOKRET = C.LUA_HOOKRET - LUA_HOOKLINE = C.LUA_HOOKLINE - LUA_HOOKCOUNT = C.LUA_HOOKCOUNT - LUA_MASKCALL = C.LUA_MASKCALL - LUA_MASKRET = C.LUA_MASKRET - LUA_MASKLINE = C.LUA_MASKLINE - LUA_MASKCOUNT = C.LUA_MASKCOUNT - LUA_ERRFILE = C.LUA_ERRFILE - LUA_NOREF = C.LUA_NOREF - LUA_REFNIL = C.LUA_REFNIL - LUA_FILEHANDLE = C.LUA_FILEHANDLE - LUA_COLIBNAME = C.LUA_COLIBNAME - LUA_TABLIBNAME = C.LUA_TABLIBNAME - LUA_IOLIBNAME = C.LUA_IOLIBNAME - LUA_OSLIBNAME = C.LUA_OSLIBNAME - LUA_STRLIBNAME = C.LUA_STRLIBNAME - LUA_MATHLIBNAME = C.LUA_MATHLIBNAME - LUA_DBLIBNAME = C.LUA_DBLIBNAME - LUA_LOADLIBNAME = C.LUA_LOADLIBNAME -) diff --git a/lua/lua_test.go b/lua/lua_test.go index 7d86c7e..d8e4887 100644 --- a/lua/lua_test.go +++ b/lua/lua_test.go @@ -1,6 +1,7 @@ package lua import ( + "fmt" "testing" "unsafe" ) @@ -78,6 +79,32 @@ func TestCheckStringFail(t *testing.T) { } } +// jea: works under OpenLibs, because generally +// we will need pcall/xpcall. +// +// See https://github.com/vxcontrol/golua#on-error-handling +// for why they are hidden. We should probably +// be hiding these then using unsafe_pcall, and +// verify that Lua code using them doesn't call +// back into Go code that panics. +/* +Shortened version of the on-error-handling link: + +Lua's exceptions are incompatible with Go. +golua works around this incompatibility by +setting up protected execution environments +in lua.State.DoString, lua.State.DoFile, and +lua.State.Call and turning every exception +into a Go panic. + +This means that: + +In general you can't do any exception handling +from Lua, pcall and xpcall are renamed to +unsafe_pcall and unsafe_xpcall. They are only +safe to be called from Lua code that never +calls back to Go. Use at your own risk. +*/ func TestPCallHidden(t *testing.T) { L := NewState() L.OpenLibs() @@ -241,8 +268,7 @@ func TestLikeUserdata(t *testing.T) { userDataProper := func(L *State) { rawptr := L.NewUserdata(uintptr(unsafe.Sizeof(Userdata{}))) - var ptr *Userdata - ptr = (*Userdata)(rawptr) + ptr := (*Userdata)(rawptr) ptr.a = 2 ptr.b = 3 @@ -343,12 +369,12 @@ func TestStackTrace(t *testing.T) { le := err.(*LuaError) - if le.Code() != LUA_ERRERR { - t.Fatalf("Wrong kind of error encountered running calls.lua: %v (%d %d)\n", le, le.Code(), LUA_ERRERR) + if le.Code != LUA_ERRRUN { + t.Fatalf("Wrong kind of error encountered running calls.lua: %v (%d %d)\n", le, le.Code, LUA_ERRERR) } - if len(le.StackTrace()) != 6 { - t.Fatalf("Wrong size of stack trace (%v)\n", le.StackTrace()) + if len(le.LuaST) != 6 { + t.Fatalf("Wrong size of stack trace (%v)\n", le) } } @@ -430,8 +456,318 @@ func TestCustomDebugHook(t *testing.T) { if err == nil { t.Fatalf("Script should have raised an error") } else { - if err.Error() != "stop" { - t.Fatal("Error should be coming from the hook") + le := err.(*LuaError) + if le.Code != 0 { + t.Fatalf("Wrong kind of lua error: %v (%d %d)\n", le, le.Code, 0) + } + if le.Msg != "stop" { + t.Fatalf("Error should be coming from the hook: %v", le) } } } + +func TestRunLuaCallback(t *testing.T) { + L := NewState() + L.OpenLibs() + defer L.Close() + + var stCb *State + var refCb, refTr int + inc, rounds := 3, 100 + regCb := func(L *State) int { + if !L.IsFunction(-1) { + t.Fatalf("Recived callback is not a lua function") + } + + stCb = L.NewThread() + refTr = L.Ref(LUA_REGISTRYINDEX) + refCb = L.Ref(LUA_REGISTRYINDEX) + + return 0 + } + + L.Register("reg_cb", regCb) + + // This code demonstrates checking that a value on the stack is a go function + L.CheckStack(1) + L.GetGlobal("reg_cb") + if !L.IsGoFunction(-1) { + t.Fatalf("IsGoFunction failed to recognize a Go function object") + } + L.Pop(1) + + // We call example_function from inside Lua VM + if err := L.DoString("r = 0; reg_cb(function(x) r = r + x; return r; end)"); err != nil { + t.Fatalf("Error executing main function: %v", err) + } + + if stCb == nil { + t.Fatalf("Lua callback is not set") + } + + for i := 0; i < rounds; i++ { + ttop := stCb.GetTop() + stCb.RawGeti(LUA_REGISTRYINDEX, refCb) + stCb.PushNumber(float64(inc)) + if err := stCb.Call(1, 1); err != nil { + t.Fatalf("Error executing callback function: %v", err) + } + if !stCb.IsNumber(-1) { + t.Fatalf("Recived result from callback is not a number") + } + cbRes := stCb.ToNumber(-1) + if cbRes != float64(inc*(i+1)) { + t.Fatalf("Expected callback result is not match value: %0.f", cbRes) + } + stCb.SetTop(ttop) + } + + L.Unref(LUA_REGISTRYINDEX, refCb) + L.Unref(LUA_REGISTRYINDEX, refTr) + + L.GetGlobal("r") + top := L.GetTop() + obsR := L.ToNumber(top) + if obsR != float64(inc*rounds) { + t.Fatalf("Result is not expected %v", obsR) + } + L.Pop(-1) +} + +func TestRunLuaCallbackFail(t *testing.T) { + L := NewState() + L.OpenLibs() + defer L.Close() + + var stCb *State + var refCb, refTr int + regCb := func(L *State) int { + if !L.IsFunction(-1) { + t.Fatalf("Recived callback is not a lua function") + } + + stCb = L.NewThread() + refTr = L.Ref(LUA_REGISTRYINDEX) + refCb = L.Ref(LUA_REGISTRYINDEX) + + return 0 + } + + L.Register("reg_cb", regCb) + + // This code demonstrates checking that a value on the stack is a go function + L.CheckStack(1) + L.GetGlobal("reg_cb") + if !L.IsGoFunction(-1) { + t.Fatalf("IsGoFunction failed to recognize a Go function object") + } + L.Pop(1) + + // We call example_function from inside Lua VM + if err := L.DoString("reg_cb(function(x) for t=1,x do print(t); end; return x; end)"); err != nil { + t.Fatalf("Error executing main function: %v", err) + } + + if stCb == nil { + t.Fatalf("Lua callback is not set") + } + + for i := 0; i < 10; i++ { + stCb.RawGeti(LUA_REGISTRYINDEX, refCb) + if i%2 == 0 { + stCb.PushNumber(3) + } else { + stCb.PushString("abc") + } + if err := stCb.Call(1, 1); err == nil && i%2 == 1 { + t.Fatal("Call did not return an error") + } else if err != nil { + le := err.(*LuaError) + + if le.Code != LUA_ERRRUN { + t.Fatalf("Wrong kind of lua error: %v (%d %d)\n", le, le.Code, LUA_ERRRUN) + } + if len(le.LuaST) != 2 { + t.Fatalf("Wrong amount of lines in stacktrace: %v (%d)\n", le, len(le.LuaST)) + } + } + stCb.Pop(-1) + } + + L.Unref(LUA_REGISTRYINDEX, refCb) + L.Unref(LUA_REGISTRYINDEX, refTr) +} + +func TestCoroutineRunning(t *testing.T) { + L := NewState() + L.OpenLibs() + defer L.Close() + + butterCalled := 0 + butter := func(L *State) int { + butterCalled++ + tot := 0.0 + tot += L.ToNumber(-1) + tot += L.ToNumber(-2) + tot += L.ToNumber(-3) + L.Pop(3) + L.PushNumber(tot) + return 1 + } + + L.Register("butter", butter) + + // This code demonstrates checking that a value on the stack is a go function + L.CheckStack(1) + L.GetGlobal("butter") + if !L.IsGoFunction(-1) { + t.Fatalf("IsGoFunction failed to recognize a Go function object") + } + L.Pop(1) + + // We call example_function from inside Lua VM + butterCalled = 0 + if err := L.DoString("a = {coroutine.resume(coroutine.create(function() return butter(4,5,6); end))}; for k,v in pairs(a) do print('a.key= ',k, ' value:', v); end; b = a[2]"); err != nil { + t.Fatalf("Error executing butter function: %v\n", err) + } + if butterCalled != 1 { + t.Fatalf("It appears the butter function wasn't actually called\n") + } + + L.GetGlobal("b") + top := L.GetTop() + obsB := L.ToNumber(top) + if obsB != 15.0 { + t.Fatalf("butter() summing 4+5+6 should have given 15, but instead got %v\n", obsB) + } +} + +func TestLuaRegsitryIsPerState(t *testing.T) { + // We test the assumption + // that the Lua Registry is shared by all + // coroutines within a main C.lua State. + // However two different C.lua_States + // are expected to have distinct registries. + // + // If validated, we'll use this fact to + // store a pointer to the main C.lua_State + // in the registry, and have all + // coroutines use the key to find their + // main state. + // + // Result: the assumption was confirmed. + // The registry is distinct per main State, + // and shared by coroutines within one state. + + L := NewState() + L.OpenLibs() + defer L.Close() + + L2 := NewState() + L2.OpenLibs() + defer L2.Close() + + key := "lua_test.my_registry_key" + val := "lua_test.my_value_for_testing" + L.PushString(key) + L.PushString(val) + L.SetTable(LUA_REGISTRYINDEX) + top := L.GetTop() + if top != 0 { + panic("expected empty stack") + } + L.PushString(key) + L.GetTable(LUA_REGISTRYINDEX) + if L.IsNil(-1) { + panic("expected value back") + } + obsVal := L.ToString(-1) + if obsVal != val { + panic("expected obsVal to match val") + } + //fmt.Printf("good: retreived val from L registry\n") + L.Pop(1) + + // now query the L2 registry + L2.PushString(key) + L2.GetTable(LUA_REGISTRYINDEX) + if !L2.IsNil(-1) { + fmt.Printf("bad, expected nil, got: '%s'\n", L2.LuaStackPosToString(-1)) + panic("expected nil back when querying L2 registry for key") + } + //fmt.Printf("good: did not retreived val from L2 registry under key\n") + + // now check that a new coroutine in L sees the same registry. + L3 := L.NewThread() + L3.PushString(key) + L3.GetTable(LUA_REGISTRYINDEX) + if L3.IsNil(-1) { + panic("expected value back") + } + obsVal3 := L3.ToString(-1) + if obsVal3 != val { + panic("expected obsVal3 to match val") + } + //fmt.Printf("good: retreived val from L3 registry\n") +} + +func assert(t *testing.T, b bool, msg string) { + if !b { + t.Fatal(msg) + } +} + +func TestToThreadDeduplicatesCoroutines(t *testing.T) { + // when ToThread encounters the same coroutine + // again, it should return the prior *State, and + // not generate a new wrapper for the same coroutine. + + L := NewState() + L.OpenLibs() + defer L.Close() + + isMain := L.PushThread() + if !isMain { + t.Fatal("should have gotten isMain true!") + } + thr := L.ToThread(-1) + if thr != L { + t.Fatal("ToThread should dedup") + } + + L2 := NewState() + L2.OpenLibs() + defer L2.Close() + + L2.PushThread() + thr2 := L2.ToThread(-1) + if thr2 != L2 { + t.Fatal("ToThread should dedup L2") + } + + if thr == thr2 { + t.Fatal("thr should not equal thr2") + } + + // make some new coroutines, make sure they are deduped. + co2b := L2.NewThread() + if co2b == thr2 || co2b == thr { + t.Fatal("co2b should not equal thr2 or thr") + } + + co2b_isMain := co2b.PushThread() + if co2b.ToThread(-1) != co2b { + t.Fatal("co2b was not deduped!") + } + assert(t, !co2b_isMain, "co2b_isMain should not have been a main thread!") + + // coroutines from Lua first + err := co2b.DoString("a = 1; return coroutine.create(function() return a; end)") + if err != nil { + t.Fatalf("DoString returned an error: %v\n", err) + } + + thr4 := co2b.ToThread(-1) + assert(t, thr4.AllCoro == nil, "non-main coroutines should have nil AllCoro maps") + assert(t, L2.AllCoro[thr4.Upos] == thr4, "thr4 should be found in L2's AllCoro, at Upos") +}