Advertisement
C0BRA

Lua++ example

Aug 18th, 2013
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. // STL
  2. #include <iostream>
  3.  
  4. // Lua
  5. #include "Lua++.hpp"
  6.  
  7. using namespace std;
  8.  
  9. void PrintTable(Lua::Variable tbl, int depth = 0)
  10. {
  11.     for(auto pair : tbl.pairs())
  12.     {
  13.         for(int i = 0; i < depth; i++)
  14.             cout << '\t';
  15.        
  16.         if(pair.second.GetType() == Lua::Type::Table)
  17.         {
  18.             cout << pair.first.ToString() << ":\n";
  19.             return PrintTable(pair.second, depth + 1);
  20.         }
  21.        
  22.         cout << pair.first.ToString() << " = " << pair.second.ToString() << "\n";
  23.     }
  24. }
  25.  
  26. list<Lua::Variable> TestFunc(Lua::State* state, list<Lua::Variable>& args)
  27. {
  28.     cout << "This is a test function, " << args.size() << " arguments provided, which are: \n";
  29.    
  30.     for(Lua::Variable& var : args)
  31.     {
  32.         if(var.GetType() == Lua::Type::Table)
  33.         {
  34.             cout << "\t" << var.GetTypeName() << ":\n";
  35.             PrintTable(var, 2);
  36.             continue;
  37.         }
  38.         cout << "\t" << var.GetTypeName() << ": " << var.ToString() << "\n";
  39.     }
  40.    
  41.     return {};
  42. }
  43.  
  44. int main(int argc, char** argv)
  45. {
  46.     using namespace Lua;
  47.    
  48.     try
  49.     {
  50.         State state;
  51.         state.LoadStandardLibary();
  52.        
  53.         // Generate a Lua variable for our function
  54.         Variable testfunc = state.GenerateFunction(TestFunc);
  55.         // Set it as a global variable
  56.         state["TestFunc"] = testfunc;
  57.        
  58.         // load and execute a file
  59.         state.DoFile("test.lua");
  60.        
  61.        
  62.         state["GiveMeAString"]("hello"); // call the function GiveMeAString, with the argument "Hello"
  63.     }
  64.     catch(Lua::Exception ex)
  65.     {
  66.         cout << "Lua exception: \n" << ex.what() << "\n";
  67.         return 1;
  68.     }
  69.    
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement