/*****************************************************************************
 * $LastChangedDate: 2010-01-24 20:49:54 -0500 (Sun, 24 Jan 2010) $
 * @file
 * @author  Jim E. Brooks  http://www.palomino3d.org
 * @brief   Exports cmd-line args into Lua as the table module.argv.
 * @remarks module.txt documents how to export new C++ classes to Lua.
 * The reason for this is that Lua won't build the usual "arg" table
 * when started non-standalone by C++.
 *//*
 * LEGAL:   COPYRIGHT (C) 2008 JIM E. BROOKS
 *          THIS SOURCE CODE IS RELEASED UNDER THE TERMS
 *          OF THE GNU GENERAL PUBLIC LICENSE VERSION 2 (GPL 2).
 *****************************************************************************/

#if ! DOXYGEN

// Avoid lua_/LUA_ which is reserved by Lua.

#include "base/module.hh"
using namespace base;
#include "lua_bind/module.hh"
#include "lua_bind/bind.hh"

namespace lua {
namespace bind {

/*****************************************************************************
 * Exports cmd-line args into Lua as the table module.argv.
 *****************************************************************************/
void
RegisterCmdLine( lua_State* L, int argc, char** argv )
{
SAVE_STACK( L );

    // Get the module table.
    // Then make the table "argv".
    lua_getglobal( L, LUABIND_MODULE_NAME );
    if ( lua_isnil( L, -1 ) )
        THROW_LUA_EXCEPTION( "bind_cmdline" );
    lua_newtable( L );              // stack[-1] : argv table
    lua_setfield( L, -2, "argv" );  // stack[-2] : module table

    // Push table argv.
    lua_getglobal( L, LUABIND_MODULE_NAME );
    lua_getfield( L, -1, "argv" );
    if ( lua_type( L, -1 ) != LUA_TTABLE )
        THROW_LUA_EXCEPTION( "bind_cmdline" );

    // For each in argv[].
    for ( int i = 0; i < argc; ++i )
    {
        // Ensure table is on top of stack.
        if ( lua_type( L, -1 ) != LUA_TTABLE )
            THROW_LUA_EXCEPTION( "bind_cmdline" );
                                           // stack[-3] table argv
        lua_pushnumber( L, double(i+1) );  // stack[-2] key
        lua_pushstring( L, argv[i] );      // stack[-1] value
        lua_settable( L, -3 );
    }

RESTORE_STACK( L );
}

} // namespace bind
} // namespace lua

#endif // ! DOXYGEN
