lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I move `resettable` to 'ltable.c'
and here is the new code more compact.

I didn't know there is a dummy hash part after `luaH_new`  allocating an empty table.

`
#define gnodelast(h) gnode(h, cast(size_t, sizenode(h)))
void luaH_resettable(lua_State *L, Table *h) {
/*need not to barrierback, because new value is NIL;*/
unsigned int i;
for (i = 0; i < h->sizearray; i++)
setnilvalue(&h->array[i]);
if (!isdummy(h->node)){
Node *n, *limit = gnodelast(h);
for (n = gnode(h, 0); n < limit; n++)   /* traverse hash part */
setnilvalue(gval(n));
}
}
`

Thanks again.

2017-01-11 20:31 GMT+08:00 Roberto Ierusalimschy <roberto@inf.puc-rio.br>:
> So we optimize our function; it looks like this
>
> `
> local tmp = {}
> function cfg_read_from_database()
> for k, v in pairs(tmp) do tmp[k] = v end
> ...
> return tmp
> end

I believe you mean "tmp[k] = nil" ?


> Here is the implementation of `table.reset`
> `
> static int treset(lua_State *L) {
> if (lua_istable(L, 1)) {
> lua_resettable(L, 1);
> }
> else {
> luaL_error(L, "bad argument to table.reset table expect got %s",
> lua_typename(L, lua_type(L, 1)));
> }
> return 0;
> }

static int treset (lua_State *L) {
  luaL_checktype(L, 1, LUA_TTABLE);
  lua_resettable(L, 1);
  return 0;
}


> LUA_API void lua_resettable(lua_State *L, int idx){
> StkId o;
> lua_lock(L);
> api_checknelems(L, 2);

*   Why 2? Probably you want 0 here (and therefore does not need the check)

> o = index2addr(L, idx);
> api_check(L, ttistable(o), "table expected");
> luaC_resettable(L, hvalue(o));
> lua_unlock(L);
> }


> void luaC_resettable(lua_State *L, Table *h) {
> /*need not to barrierback, because new value is NIL*/
> Node *n, *limit = gnodelast(h);
> unsigned int i;
> for (i = 0; i < h->sizearray; i++){
> TValue *cell = &h->array[i];
> setnilvalue(cell);
> }
> for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */
> TValue *cell = gval(n);
> if (!ttisnil(cell))

*   it seems cleaner to just set nil without the previous test

> setnilvalue(cell);
> }
> }
> `
>
> Are there any issues/pitfalls of my implementation. Or any advices for me?
> Many thanks.

If the fields are all the same (the same "type" of table), you wouldn't
need to clean the table before setting them (the new values would
overwrite the old ones).

-- Roberto