Files
ljkiwi/ckiwi/luakiwi-int.h
2024-02-22 03:54:51 -06:00

85 lines
2.1 KiB
C

#ifndef LUAKIWI_INT_H_
#define LUAKIWI_INT_H_
#include "luacompat.h"
#define ARR_COUNT(x) (sizeof(x) / sizeof((x)[0]))
#if defined(__GNUC__) && !defined(LKIWI_NO_BUILTIN)
#define l_likely(x) (__builtin_expect(((x) != 0), 1))
#define l_unlikely(x) (__builtin_expect(((x) != 0), 0))
#else
#define l_likely(x) (x)
#define l_unlikely(x) (x)
#endif
#ifndef LKIWI_NO_STALLOC
#if defined(_MSC_VER)
#include <malloc.h>
static inline void* stalloc(size_t sz) {
void* p = _malloca(sz);
if (!p) {
luaL_error(L, "out of memory");
}
return p;
}
#define stfree(ptr) _freea(ptr)
#else
#include <alloca.h>
#define stalloc alloca
#define stfree(ptr)
#endif
#else
#include <stdlib.h>
static inline void* stalloc(size_t sz) {
void* p = malloc(sz);
if (l_unlikely(!p)) {
luaL_error(L, "out of memory");
}
return p;
}
#define stfree(ptr) free(ptr)
#endif
// Lua 5.1 compatibility for missing lua_arith.
static void compat_arith_unm(lua_State* L) {
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 501
lua_Number n = lua_tonumber(L, -1);
if (n != 0 || lua_isnumber(L, -1)) {
lua_pop(L, 1);
lua_pushnumber(L, -n);
} else {
if (!luaL_callmeta(L, -1, "__unm"))
luaL_error(L, "attempt to perform arithmetic on a %s value", luaL_typename(L, -1));
lua_replace(L, -2);
}
#else
lua_arith(L, LUA_OPUNM);
#endif
}
// This version supports placeholders.
static void setfuncs(lua_State* L, const luaL_Reg* l, int nup) {
luaL_checkstack(L, nup, "too many upvalues");
for (; l->name != NULL; l++) { /* fill the table with given functions */
if (l->func == NULL) /* place holder? */
lua_pushboolean(L, 0);
else {
int i;
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -nup);
lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
}
lua_setfield(L, -(nup + 2), l->name);
}
lua_pop(L, nup); /* remove upvalues */
}
#define newlib(L, l) (lua_newtable((L)), setfuncs((L), (l), 0))
#endif // LUAKIWI_INT_H_