lua-users home
lua-l archive

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


Yes, something like that would be very welcome.

I thought in something like this:

t = table.createtable( narr, nrec, def_func )

where, narr is for array elements and nrec is for non-array elements,
like in lua_createtable function. But here, we could have a third
parameter (def_func) which can be de default value to fill the table.
This parameters could be a function too, and in this case the function
would be called for each element of the new table. This function receive
a parameter "pos" (position element) with the element number, for array
elements or nil for a non-array elements. Then it returns one or two
values, the first for the value for the element and, in case of a
non-array element, the second returned value should be the key of the
cell. Like this example below.

t = table.createtable( 5, 0, 10 ) --> create a new table with five
elements and fill all of then with the number ten

f = function( pos ) --> the function to fill the array elements
according to the element type (array or non-array)
local counter = 0
if pos then
return pos * 2
end
counter = counter + 1
return counter * 3 , 'element' .. tostring( counter )
end

t = table.createtable( 5, 5, f ) --> create a new table with five array
elements, five no-array elements and
-- fill all of then with the result of the function 'f'

What do you think?

[]'s

Marco Antonio Abreu


2009/3/13 Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br>
> Here is a helper function that creates an empty table where you can supply
> the parameters you want to create the table with:
> function newtable(arraysize, hashsize)
>     return loadstring("return {" .. ("nil,"):rep(arraysize) ..
> ("[0]=nil,"):rep(hashsize) .. "}")()
> end

I think the OP wants a C binding to lua_createtable, such this:

static int luaB_createtable (lua_State *L) {
 lua_createtable(L,luaL_optstring(L,1,0),L_optstring(L,2,0));
 return 1;
}