lua-users home
lua-l archive

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

Sorry guys, I made two mistakes in my code.
First, the local variable 'counter' should be defined outside the function. Second, the function 'f' should return the value or the key and the value, not the opposite, like I said. This order is follow for the 'table.insert' function parameters.


2009/3/14 Marco Antonio Abreu <>
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
counter = counter + 1
return counter * 3 , 'element' .. tostring( counter )

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?


Marco Antonio Abreu

2009/3/13 Luiz Henrique de Figueiredo <>

> 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) {
 return 1;