lua-users home
lua-l archive

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

Hi Guys,

I want to reopen the topic about table constructor created by Jason Santos:

"Is there a reason why there is no function in the table library to mirror lua_createtable() from the C API?

Would it be a good idea to add such a function?

If there are performance tuning opportunities to be explored by reducing the amount of table.inserts (Yes, I've read Roberto's article on Lua Gems), I would like to be able to make them dynamically and in pure lua".

I suppose it will be very useful if we could create a table with all occurrencies we need direct from Lua. Like Luiz Henrique said "a C binding for lua_createtable" should be nice, but I thought in something beyond. I suppose it could be interesting if we could give the default value to the occurrences created  by the function and, in case of a function, it could be called to return the valeu and its key. What do you think about this?

function createtable( a, n, f, c )

    collectgarbage( 'stop' )
    -- this line below should be the memory allocation with all necessary space for the occurencies - lua_createtable( L, a, n )
    local result = loadstring( 'return {' .. string.rep( 'false,', n + a ) .. '}' )()
    if c or type( f ) ~= 'function' then
        for i = 1, a do
            result[ i ] = f
        for i = 1, n do
            result[ tostring( i ) ] = f
        local k, v

        for i = 1, a do
            v, k = f( i, 'a' )
            result[ k or i ] = v

        for i = 1, n do
            v, k = f( i, 'n' )
            result[ tostring( k or i ) ] = v

    collectgarbage( 'restart' )
    return result

Marco Antonio Abreu
Analista de Sistemas