2

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)
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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.