lua-users home
lua-l archive

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



When I first started my Lua project, I ran into a problem with it crashing as the standard Lua libraries were loading.  It turned out that my heap size was too small.  That’s when I discovered that Lua libraries are loaded into the heap, in my embedded case, copying the routines from flash into DRAM (or so I’ve been told).  Not an efficient use of memory.  I understand that eLua leaves the libraries in non-volatile memory.


My question is this; I assume libraries that I create will also be loaded into the heap.  Is this correct?


For example, following is a simple library I created allowing a Lua script to manipulate a C structure used to send a network message:



  messageHeader Library


static const struct luaL_Reg messageHeaderLib [] =


  {"new", newMessageHeader},

  {"set", setMessageHeader},

  {"get", getMessageHeader},




static int newMessageHeader(lua_State *L)


  LevitonCAN_ApplicationCommonTypes *messageHeader;

  messageHeader = (LevitonCAN_ApplicationCommonTypes *)lua_newuserdata(L, sizeof(LevitonCAN_ApplicationCommonTypes));


  messageHeader->Address.D8.DestinationSubnet = 0xFF;

  messageHeader->Address.D8.DestinationNode   = 0xFF;

  messageHeader->returnAckNumber              = 0;

  messageHeader->priority                     = 0;

  messageHeader->serviceType                  = 0;

  messageHeader->priorityOverride             = 0;

  messageHeader->LC3_DestinationMulticast     = 0;

  return 1; /* new userdatum is already on the stack */



static int setMessageHeader(lua_State *L)


  LevitonCAN_ApplicationCommonTypes *messageHeader = (LevitonCAN_ApplicationCommonTypes *)lua_touserdata(L, 1);

  int subnet = luaL_checkint(L, 2);

  int nodeID = luaL_checkint(L, 3);

  luaL_argcheck(L, messageHeader != NULL, 1, "'messageHeader' expected");

  luaL_argcheck(L, 0 <= subnet && subnet < 255, 2, "subnet out of range");

  luaL_argcheck(L, 1 <= nodeID && nodeID < 255, 3, "nodeID out of range");

  messageHeader->Address.D8.DestinationSubnet = subnet;

  messageHeader->Address.D8.DestinationNode   = nodeID;

  return 0;



static int getMessageHeader(lua_State *L)


  LevitonCAN_ApplicationCommonTypes *messageHeader = (LevitonCAN_ApplicationCommonTypes *)lua_touserdata(L, 1);

  luaL_argcheck( L, messageHeader != NULL, 1, "'messageHeader' expected" );

  lua_pushnumber( L, messageHeader->Address.D8.DestinationSubnet );

  lua_pushnumber( L, messageHeader->Address.D8.DestinationNode );


  return 2;



int luaopen_messageHeader (lua_State *L)


  luaL_newlib(L, messageHeaderLib);

  return 1;




The library is load as follows:


  // Register messageHeader API Library





  luaL_requiref(L, "mh", luaopen_messageHeader, 1);