USEFUL LINKS:
http://www.lua.org/
http://www.lua.org/manual/5.1/#index (This entire page in general is very useful!)
First off lets get lua all setup so get the includes remember to extern c them because the lua API was originally written for C unless your using C of course
Code: Select all
extern "C" {
#include <lua.h> //Use quotations if < > doesn't work for you
#include <lualib.h>
#include <lauxlib.h>
}
Code: Select all
lua_State* L = lua_open();
Code: Select all
int main()
{
luaL_openlibs(L);
cout << "Lua Libraries Initialized!" << endl;
return 0;
}
first off create a static int function like so:
Code: Select all
static int RandomLuaFunction(lua_State *L)
{
return 0;
}
Code: Select all
static int ReturnValFunc(lua_State *L)
{
int x = 10;
lua_pushnumber(L,x); //Pushes the number out to the function, lua does more than just numbers it can do strings and such!
return 1; //return 1 arguement
}
static int GetValFunc(lua_State *L)
{
int n = lua_gettop(L); //Get the ammount of arguements being passed
if(n == AMOUNT YOU WANT){
GetValFuncVal = lua_tonumber(L,-1) //Get The Last Arguement Being passed
}
else
{
cout << "Error 1 Arguement Expected Got:" << n << endl;
}
return 0;
}
bool Toggle = false;
//This function will be used to represent that you don't always need arguements going back and forth it could be something like a toggle!
static int ToggleExample(lua_State *L)
{
if (Toggle == false)
{
Toggle = true;
}
else
{
Toggle = false;
}
}
so i prefer to split my function registration into a function that will be called during initialization, like so:
Code: Select all
void RegisterLuaFunctions(lua_State *L)
{
lua_register(L,"ReturnVal",ReturnValFunc);
lua_register(L,"GetVal",GetValFunc);
lua_register(L,"Toggle",ToggleExample);
cout << "Lua Functions Registered!" << endl;
}
Code: Select all
local x = ReturnVal()
GetVal(x-10)
Toggle()
Code: Select all
int main()
{
luaL_openlibs(L); // Open the libs
RegisterLuaFunctions(L); //Register Functions
luaL_dofile(L,"SCRIPTWITHFILEPATH"); // Will execute a whole script at the designated file path
cout << "Lua Libraries Initialized!" << endl;
return 0;
}
Code: Select all
luaL_dostring(L,"Toggle()");
And lastly don't forget to close lua when your done using the lua_close function:
Code: Select all
lua_close(L);
Im aware this may not be the best way to have lua in but hey it has worked for me, anyways this is the bare minimum of what you could be doing if you want more information such as more luaL_ and lua_ functions check out the links above they provide pretty good documentaion if you don't understand or think they are to vague just GOOGLE it google is bound to be your best option and will yield at least some useful results. Regardless i hope this helps you with lua implementation and i hope its not to terribly flawed XD and have fun scripting!