Add arrays to Lua (#222)

You can now have O(1) length and append.
This commit is contained in:
Paul Kulchenko 2021-08-06 04:55:01 -07:00 committed by GitHub
parent b142ea7176
commit 55a15c204e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 557 additions and 20 deletions

View file

@ -18,6 +18,7 @@
#include "third_party/lua/lstate.h"
#include "third_party/lua/lstring.h"
#include "third_party/lua/ltable.h"
#include "third_party/lua/larray.h"
#include "third_party/lua/ltm.h"
#include "third_party/lua/lua.h"
#include "third_party/lua/lundump.h"
@ -312,6 +313,12 @@ LUA_API int lua_isuserdata (lua_State *L, int idx) {
}
LUA_API int lua_isarray (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
return (isvalid(L, o) && ttype(o) == LUA_TTABLE && hvalue(o)->truearray);
}
LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
const TValue *o1 = index2value(L, index1);
const TValue *o2 = index2value(L, index2);
@ -759,6 +766,41 @@ LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
}
LUA_API void lua_createarray (lua_State *L, int narray) {
Array *a;
lua_lock(L);
a = luaA_new(L);
setavalue2s(L, L->top, a);
api_incr_top(L);
if (narray > 0)
luaA_resize(L, a, narray);
luaC_checkGC(L);
lua_unlock(L);
}
LUA_API void lua_resize (lua_State *L, int idx, unsigned int size) {
TValue *o;
Table *t;
unsigned int i, oldsize;
lua_lock(L);
o = index2value(L, idx);
api_check(L, ttistable(o), "table expected");
t = hvalue(o);
oldsize = t->sizeused;
if (size > luaH_realasize(t)) {
luaH_resizearray(L, t, size);
}
lua_unlock(L);
/* set removed elements to nil when shrinking array size */
for(i = size + 1; i <= oldsize; i++) {
lua_pushnil(L);
lua_seti(L, idx, i);
}
t->sizeused = size;
}
LUA_API int lua_getmetatable (lua_State *L, int objindex) {
const TValue *obj;
Table *mt;
@ -867,7 +909,10 @@ LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
lua_lock(L);
api_checknelems(L, 1);
t = index2value(L, idx);
if (luaV_fastgeti(L, t, n, slot)) {
if (ttisarray(t)) {
luaA_setint(L, avalue(t), n, s2v(L->top - 1));
}
else if (luaV_fastgeti(L, t, n, slot)) {
luaV_finishfastset(L, t, slot, s2v(L->top - 1));
}
else {