-
Notifications
You must be signed in to change notification settings - Fork 28
The Global Environment
One of the uses of a Lua script is as a configuration file. What this means is in your Lua script, you declare a bunch of variables that your program will expect to be able to read. A configuration file might look like this:
-- config.lua
-- Our program's configuration file
width = 1024
height = 768
windowTitle = "My game"
This is probably a small configuration file for your game. In order to get the variables declared in the global scope, we need to access the Global Environment:
// this function returns the Global Environment.
lua.GetGlobalEnvironment();
By calling this method GetGlobalEnvironment()
, we will be given an object that will give us access to all global variables. How do we use this in the context of a C++ program? Have a look at the program below:
#include <fstream>
#include <streambuf>
#include <string>
#include <iostream>
#include <luacppinterface.h>
int main()
{
std::ifstream file("config.lua");
std::string script((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
Lua lua;
int width = lua.GetGlobalEnvironment.Get<int>("width"); // get the width
int height = lua.GetGlobalEnvironment.Get<int>("height"); // get the height
std::string windowTitle = lua.GetGlobalEnvironment.Get<std::string>("windowTitle");
std::cout << result << std::endl;
return 0;
}
Here, if you pay attention, we retrieve the Global Environment and call Get to get integers and Getstd::string to get strings.
If you remember your Lua well, variables declared without the keyword "local" are global variables.
So what's really going on here? What is this magical object that the GetGlobalEnvironment()
method returns? Well, if you remember how Lua works, GetGlobalEnvironment()
, like the __G
variable returns a table in the form of a LuaTable C++ object. This LuaTable is the class that has the Get<T>
methods that we use to extract the values from each of the variables.
This then brings us to the more central topic of the LuaTable object, arguably the most important object in Lua.
Next: The LuaTable Object