Skip to content

Commit

Permalink
Pre-grow roll/unroll tables
Browse files Browse the repository at this point in the history
  • Loading branch information
CannibalVox committed Apr 18, 2020
1 parent 59a6462 commit 1980b51
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
21 changes: 20 additions & 1 deletion go_luatypes.c
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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++) {
Expand Down
3 changes: 3 additions & 0 deletions go_luatypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion local_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 1980b51

Please sign in to comment.