From 1980b51a9c593c5c51f6ff2b0c49292006603d19 Mon Sep 17 00:00:00 2001 From: Stephen Baynham Date: Sat, 18 Apr 2020 12:36:28 -0700 Subject: [PATCH] Pre-grow roll/unroll tables --- go_luatypes.c | 21 ++++++++++++++++++++- go_luatypes.h | 3 +++ local_table.go | 2 +- 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/go_luatypes.c b/go_luatypes.c index cd03b12..110b9a9 100644 --- a/go_luatypes.c +++ b/go_luatypes.c @@ -120,6 +120,8 @@ lua_result unroll_table(lua_State *_L, lua_value *table) { unrolled->first = NULL; unrolled->last = NULL; + unrolled->arraySize = 0; + unrolled->hashSize = 0; lua_pushnil(_L); // First key to start iteration @@ -167,6 +169,21 @@ lua_result unroll_table(lua_State *_L, lua_value *table) { } lua_table_entry *entry = chmalloc(sizeof(lua_table_entry)); + + //We should increment the array count or hash count + if (key.value->valueType == LUA_TNUMBER) { + float number = key.value->data.numberVal; + + if (number > 0) { + //We can be off by a little if we need to, so don't bohter figuring out + //if number is an integer + unrolled->arraySize = unrolled->arraySize+1; + } else { + unrolled->hashSize = unrolled->hashSize+1; + } + } else { + unrolled->hashSize = unrolled->hashSize+1; + } entry->key = key.value; entry->value = value.value; entry->next = NULL; @@ -301,7 +318,7 @@ lua_return pop_lua_values(lua_State *_L, int valueCount) { } lua_err *push_unrolled_table(lua_State *_L, lua_unrolled_table *table) { - lua_newtable(_L); + lua_createtable(_L, table->arraySize, table->hashSize); lua_table_entry *next = table->first; while (next != NULL) { lua_err *err = push_lua_value(_L, next->key); @@ -400,6 +417,8 @@ lua_unrolled_table *build_unrolled_table(int entries) { lua_unrolled_table *table = chmalloc(sizeof(lua_unrolled_table)); table->first = NULL; table->last = NULL; + table->arraySize = 0; + table->hashSize = 0; lua_table_entry *entry = NULL; for (int i = 0; i < entries; i++) { diff --git a/go_luatypes.h b/go_luatypes.h index 4a1e379..2e0d33b 100644 --- a/go_luatypes.h +++ b/go_luatypes.h @@ -56,6 +56,9 @@ typedef struct lua_table_entry lua_table_entry; struct lua_unrolled_table { lua_table_entry *first; lua_table_entry *last; + + unsigned int arraySize; + unsigned int hashSize; }; typedef struct lua_unrolled_table lua_unrolled_table; diff --git a/local_table.go b/local_table.go index dec0ed5..ff292c6 100644 --- a/local_table.go +++ b/local_table.go @@ -22,7 +22,7 @@ func (table *LocalLuaTable) convertSingleUnrolledValue(value *C.struct_lua_value } func (table *LocalLuaTable) convertUnrolledTable(unrolled *C.struct_lua_unrolled_table) (map[interface{}]interface{}, error) { - retVal := make(map[interface{}]interface{}) + retVal := make(map[interface{}]interface{}, unrolled.arraySize+unrolled.hashSize) var entry *C.struct_lua_table_entry entry = unrolled.first