lua_Integer and lua_createtable (table size limit)
Asked Answered
Z

1

6

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?

Zinkenite answered 11/1, 2015 at 3:48 Comment(1)
This question seems more suitable to the Lua mailing list.Vanderpool
R
5

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).

Rivera answered 12/1, 2015 at 15:23 Comment(1)
Thanks for taking the time to answer this. I was actually writing up a post to lua-l when I saw your answer.Zinkenite

© 2022 - 2024 — McMap. All rights reserved.