Using cjson in embedded Lua in C++ - c++

I have a C++ program that creates a lua_State and run custom Lua script. If I would like to have the lua_State pre-load cjson instead of requiring calling "require" in the Lua code, can I know whether it is possible and how can I do that?

Yes, it's possible. Use luaL_requiref for that. Use this or this function as argument. You'll need to link the cjson code to your executable, and the compiler would probably appreciate a function declaration for the luaopen_* functions. If you use Lua 5.1 (which doesn't have luaL_requiref yet) you can use or steal from Compat-5.3.

You could call require once through C++ and make a global variable out of the return value if you don't want to call require in scripts.
For example in C++ do:
if (luaL_dostring(L, "cjson = require(\"cjson\")")) // run code
std::cout << luaL_checkstring (L, -1) << std::endl; // print error
and after that you can use cjson in your scripts like cjson.new() without any require or such calls as it exists as a global variable.
Since require was used by C++ then calling require in lua later on will not run the cjson file again unlike using dofile or similar

Related

Calling a native C function after making a variable with that name

I have a pretty large application which holds most of the program data in a large container object called system.
So I access things all the time, e.g. printf("%s\n",system.constants.jobname);, and changing the name of system is undesirable.
I learned later that the function system exists as a native C function for running terminal commands, e.g. system("rm *.txt");
My problem is that I get compilation errors trying to use system as a function because it's already defined as an object.
Is there any way one can call a native C function explicitly ignoring programmatically defined variables? Or give the native system function an alias? (I'm using C++ so using it would be fine)
If you're using C++, system is in the global namespace. Assuming you've put your stuff in a proper namespace (you have, right?) you can refer to it as ::system.
Assuming using shared libraries is an acceptable solution, you can do this.
Create another C file which will not use your system container. Now write a function my_system that is a wrapper to system.
By wrapper I mean, it takes the same argument and calls system and returns what system returns.
Don't forget to export my_system
Now compile this as a dll (or .so on *NIX).
In your main project, load the dll and get a handle. Now query for address of my_system on the handle and make the call using function pointer.

LuaBridge running C++ main function in lua for Love2D

Here is my C++ main function :
int main() {
lua_State* L = luaL_newstate();
luaL_openlibs(L);
getGlobalNamespace(L).
beginNamespace("o").
beginClass<Object>("Object").
addConstructor<void (*) (double, double)>().
addProperty("width", &Object::getWidth, &Object::setWidth).
addProperty("height", &Object::getHeight, &Object::setHeight).
addProperty("x", &Object::getX, &Object::setX).
addProperty("y", &Object::getY, &Object::setY).
endClass().
endNamespace();
lua_pcall(L, 0, 0, 0);
luaL_dofile(L, "main.lua");}
And here is my main.lua for Love2D
function love.load()
obj = o.Object(10, 20) end
When i tried to run it with love it says that obj is a nil value and i realized that Love2D doesn't run my main function in C++ to create the object class.
How do i call a C++ main function in Lua using LuaBridge?
What you are doing is using two separate programs: the one you build with your "main function", and the actual Love2D executable. They're separate executables; they have no more relation to one another than lua.exe has to python.exe.
What you appear to be wanting to do is write a C++ library that is used by Love2D. You can do that, but it requires that you write, not a C++ program, but a dynamic library. You have to write a Lua C-module.
How you write a dynamic library depends on your platform of choice. But that dynamic library must export the appropriate functions, as detailed in the Lua 5.1 documentation. If your C module is named "test", then it must export a function called luaopen_test.
The job of this function is essentially what your main does. Your luaopen_ function does not have to create a Lua state; it will be given one. It's job is to return a table that contains the functions and APIs you want to export in your module. So it registers everything with Lua as needed.
Your main puts its stuff in the global "namespace", but this is generally considered quite rude. It's better to build a local table and put your stuff there, returning the table as the return value. I'm not familiar with LuaBridge's API, so I have no idea how to go about doing that.
Worst case is that you could build a global table as you currently do, but after building it, load it into a local table, clear the global entry, then return the table.

directly calling from what user inputs and Is there a concept of generating a function at run time?

Is there a way out to call a function directly from the what the user inputs ?
For example : If the user inputs greet the function named greet is called.
I don't want any cases or comparison for the call to generate.
#include <iostream>
#include<string>
using namespace std;
void nameOfTheFunction(); // prototype
int main() {
string nameOfTheFunction;
getline(cin,nameOfTheFunction); // enter the name of Function
string newString = nameOfTheFunction + "()"; // !!!
cout << newString;
// now call the function nameOfTheFunction
}
void nameOfTheFunction() {
cout << "hello";
}
And is there a concept of generating the function at run time ?
You mean run time function generation ??
NO.
But you can use a map if you already know which all strings a user might give as input (i.e you are limiting the inputs).
For the above you can probably use std::map &lt std::string, boost::function &lt... &gt &gt
Check boost::function HERE
In short, no this isn't possible. Names in C++ get turned into memory offsets (addresses), and then the names are discarded**. At runtime C++ has no knowledge of the function or method names it's actually running.
** If debug symbols are compiled in, then the symbols are there, but impractical to get access to.
Generating a function at runtime has a lot of drawbacks (if it is possible at all) and there is generally no good reason to do it in a language like C++. You should leave that to scripting languages (like Perl or Python), many offer a eval() function that can interpret a string like script code and execute it.
If you really, really need to do have something like eval() in a compiled language such as C++, you have a few options:
Define your own scripting language and write a parser/interpreter for it (lots of work)
Define a very simple imperative or math language that can be easily parsed and evaluated using well-known design patterns (like Interpreter)
Use an existing scripting language that can be easily integrated into your code through a library (example: Lua)
Stuff the strings of code you want to execute at runtime through an external interpreter or compiler and execute them through the operating system or load them into your program using dlopen/LoadLibrary/etc.
(3.) is probably the easiest and best approach. If you want to keep external dependencies to a minimum or if you need direct access to functionality and state inside your main program, I suggest you should go for (2.) Note that you can have callbacks into your own code in that case, so calling native functions from the script is not a problem. See here for a tutorial
If you can opt for a language like Java or C#, there's also the option to use the compiler built into the runtime itself. Have a look here for how to do this in Java

How to wrap an init/cleanup function in Boost python

I recently discovered the existence of boost-python and was astonished by it's apparent simplicity. I wanted to give it a try and started to wrap an existing C++ library.
While wrapping the basic library API calls is quite simple (nothing special, just regular function calls and very common parameters), I don't know how to properly wrap the initialization/cleanup functions:
As it stands, my C++ library requires the caller to first call mylib::initialize() when the program starts, and to call mylib::cleanup() before it ends (actually there is also an initializer object that takes care of that, but it is probably irrelevant).
How should I wrap this using boost python ?
Forcing a Python user to call mymodule.initialize() and mymodule.cleanup() seems not very pythonic. Is there any way to that in an automatic fashion ? Ideally, the call to initialize() would be done transparently when the module is imported and the call to cleanup() also done when the python script ends.
Is there any way to do that ? If not, what is the most elegant solution ?
Thank you.
You could try to do a guard object and assign it to a hidden attribute of your module.
struct MyLibGuard
{
MyLibGuard() { myLib::initialize();}
~MyLibGuard() { myLib::cleanup();}
};
using namespace boost::python;
BOOST_PYTHON_MODULE(arch_lib)
{
boost::shared_ptr<MyLibGuard> libGuard = new MyLibGuard();
class_<MyLibGuard, boost::shared_ptr<MyLibGuard>, boost::noncopyable>("MyLibGuard", no_init);
scope().attr("__libguard") = libGuard;
}

Interpreter in C++: Function table storage problem

In my interpreter I have built-in functions available in the language like print exit input, etc.
These functions can obviously be accessed from inside the language. The interpreter then looks for the corresponding function with the right name in a vector and calls it via a pointer stored with its name.
So I gather all these functions in files like io.cpp, string.cpp, arithmetic.cpp. But I have to add every function to the function list in the interpreter in order for it to be found.
So in these function files I have things like:
void print( arg )
{
cout << arg.ToString;
}
I'd add this print function to the interpreter function list with:
interpreter.AddFunc( "print", print );
But where should I call the interpreter.AddFunc?
I can't just put it there below the print function as it has to be in a function according to the C++ syntax.
Where and how should all the functions be added to the list?
In each module (io, string, etc.), define a method that registers the module with the interpreter, e.g.:
void IOModule::Register(Interpreter &interpreter) {
interpreter.AddFunc( "print", print );
//...
}
This can also be a normal function if your module is not implemented in a class.
Then in your application's main initialization, call the register method of all modules.
This approach helps keep things modular: The main application initialization needs to know which modules exist, but the details of which functions are exported are left to the module itself.
The simplest is to keep a map of function names to function pointers and load that at program startup. You already have the functions linked into the interpreter executable, so they are accessible at the time main() is called.
You can also come up with a scheme where functions are defiled in the dynamic libraries (.dll or .so depending on the platform) and some configuration file maps function names to libraries/entry points.
Is everything included in every interpreter? If so, I would recommend adding it either in a constructor (assuming the interpreter is an object) or an init method.
If not, you may want to consider adding an "include" type directive in your language. Then you do it when you encounter the include directive.