开发者

Passing a Lua variable to C

I am embedding Lua in a C++ application and I want to provide a print() like function (or maybe simply override Lua's print function), so that I can pass variables of simple datatypes (string, boolean and number) into my C++ app as strings.

So what I am looking to do is to have a C++ function, which I export to Lua, called my_print()

I can then call my_print() in a Lua chunk like so:

a = 22/7
b = false
c = 42
my_print('The value of variable a is: ' .. a)开发者_JS百科
my_print('b: ' .. b)
my_print('c is: ' .. c)

Each time my_print() is called, it will pass a C++ string to the C++ app. I have had a look at the Lua C API, I suspect that I will have to use lua_gettop(L), lua_type() etc.

A little snippet on how to get started in writing such a C/C++ function that can be exported to Lua and used in the manner described above, would be very much appreciated.


Have you looked at the implementation of print and other functions from the standard Lua library? You may want to start with lmathlib.c. See http://www.lua.org/source/5.1/ . Try also etc/min.c from the source tarball.


You should take a look at this http://www.lua.org/source/5.1/lbaselib.c.html#luaB_tostring

Here they are returning the string but it is a good starting point. I can't really disagree with lhf but this deals with the meta table's __tostring while min.c does not. I think that is pretty important, especially when you get into Lua oo.


If you do it like you have in your example, the one argument my_print gets is already a string (or better lua_lstring), because the values get coerced to the string type by the concatenation operator ... Only the false thing won't work. so just passing tostring(var) will work in most cases. For more control you might take a look at string.format.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜