lua-users home
lua-l archive

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


Hi, all

I am using Lua 5.1.5 on Cygwin environment. I have a problem in writing a C function that receives a empty table from Lua, fills it with some entries and then returns the table back to Lua, as shown below:

Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> require 'mylib'
> tbl1 = mylib.updateTable({})

The call to mylib.updateTable() never return (blocked forever). The C function (l_updateTable()) is coded as below:

void addEntries(lua_State* L) {  
  int i;
  char* keys[] = { "One", "Two", "Three" };
  char* values[]  = { "Value of One", "Value of Two", "Value of Three" };
  for(i = 0; i < 3; i++) {
    lua_pushstring(L, keys[i]);
    lua_pushstring(L, values[i]);
    lua_rawset(L, -3);
  }
}

static int l_updateTable(lua_State *L) {   
  luaL_checktype(L, -1, LUA_TTABLE);
  addEntries(L);
  return 1; /* return table */
}

For testing purpose, I created the empty table inside my C function (instead of passing from Lua). This time I can get the expected result.

> tbl1 = mylib.newTable()
> for k,v in pairs(tbl1) do print(k,v) end
One     Value of One
Three   Value of Three
Two     Value of Two

static int l_newTable(lua_State *L) 
  lua_newtable(L);
  addEntries(L);
  return 1; /* return table */
}

Adding to my surprise is, on Linux environment, both functions work as expected.

So, what could be wrong with my implementation (the one that receives an empty table from Lua) on Cygwin? 

Hope you can provide some clue on this. I attached my C code for your reference.

Thanks.

Regards,

KHT

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"

void addEntries(lua_State* L) 
{  
  int i;
  char* keys[] = { "One", "Two", "Three" };
  char* values[]  = { "Value of One", "Value of Two", "Value of Three" };
  for(i = 0; i < 3; i++) {
    lua_pushstring(L, keys[i]);
    lua_pushstring(L, values[i]);
    lua_rawset(L, -3);
  }
}

static int l_updateTable(lua_State *L)
{   
  luaL_checktype(L, -1, LUA_TTABLE);
  addEntries(L);
  return 1; /* return table */
}

static int l_newTable(lua_State *L)
{ 
  lua_newtable(L);
  addEntries(L);
  return 1; /* return table */
}

static const struct luaL_Reg mylib [] = {
  {"newTable", l_newTable},
  {"updateTable", l_updateTable},
  {NULL, NULL}
};

int luaopen_mylib(lua_State *L) 
{
  luaL_register(L, "mylib", mylib);
  return 1;
}