开发者

luabind - variable number of parameters

How can I bind a function with luabind that 开发者_高级运维accept a variable number of parameters ? Basically, I want to write my own print() function.

I know that the object class in luabind as a parameter can accept any data type, the best would be to received a dynamic table of luabind::object as a parameter.


I have made a mix between pure lua C API and luabind:

int myPrint(lua_State* L)
{
    int argCount = lua_gettop(L);

    for(int i = 1; i <= argCount; i++)
    {
        luabind::object obj(luabind::from_stack(L, i));

        switch(luabind::type(obj))
        {
            case LUA_TSTRING:
                cout << luabind::object_cast<std::string>(obj);
                break;
            case LUA_TNUMBER:
                cout << luabind::object_cast<double>(obj);
                break;
            case LUA_TBOOLEAN:
                cout << boolalpha << luabind::object_cast<bool>(obj);
                break;
            case LUA_TNIL:
                cout << "#Nil#";
                break;
            default:
                cout << "#Unknown type '" << luabind::type(obj) << "'#";
                break;
        }
    }

    cout << endl;

    return 0;
}


It looks like luabind doesn't support that. However, given that it's a global function rather than a method on some class, couldn't you just could use the regular C API for it? It's very easy to use. For instance, here's a vararg function that returns the types of it's arguments:

static int types (lua_State* L) {
   int argc = lua_gettop(L);
   for (int i=1; i <= argc; ++i) {
      lua_pushstring(L, lua_typename(L, lua_type(L, i)));
   }
   return argc;
}

...

lua_register(L, "types", types);


Your better off using string.format and passing the remaining string into a log function.

function printf(...)
    log(string.format(...))
end

This is what I tend to do and then my application can decide to send the log output to a file or console.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜