Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua_Integer and lua_createtable (table size limit)

In Lua 5.3 table related functions in the C API receive and return lua_Integer.

void lua_rawgeti (lua_State *L, int idx, lua_Integer n);
void lua_rawseti (lua_State *L, int idx, lua_Integer n);
lua_Integer luaL_len (lua_State *L, int index);

But, lua_createtable still receives int.

void lua_createtable (lua_State *L, int narr, int nrec);

In the example function below the length of the source table is used to create a copy which is the same size.

static int copy_sequence(lua_State *L) {
   lua_Integer len, i;
   luaL_checktype(L, 1, LUA_TTABLE);
   len = luaL_len(L, 1);
   lua_createtable(L, (int)len, 0); /* conversion warning */
   for (i = 1; i <= len; i++) {
      lua_rawgeti(L, 1, i);
      lua_rawseti(L, -2, i);
   }
   return 1;
}

But, a cast is required to silence the warning:

warning: conversion to ‘int’ from ‘lua_Integer’ may alter its value [-Wconversion]

Searching on the Lua mailing list I found the following thread which is about Lua 5.2 (applies to earlier versions too I'm assuming):

Quote: Roberto Ierusalimschy (7 Aug 2012)

The size of tables is already limited to 2147483647 elements. Lua internally uses 'int' to index all its arrays (except for strings/byte arrays). It is a pain to work with unsigned values (such as size_t) everywhere; ptrdiff_t has no garanties at all.

Is this still the case for Lua 5.3 which uses long long for lua_Integer? Is the cast to int from lua_Integer as used in the example above safe in Lua 5.3?

like image 596
Adam Avatar asked Jan 11 '15 03:01

Adam


1 Answers

The size of a table (number of elements) is still limited to 'int'. That does not prevent a table from having arbitrary lua_Integer keys (as long as the table is not a proper sequence).

like image 131
Roberto Ierusalimschy Avatar answered Oct 20 '22 20:10

Roberto Ierusalimschy