Posted by
| Nick Gammon
Australia (22,975 posts) bio
Forum Administrator |
Message
| Now let's try a more elaborate example. This one will read in a file (an obvious example here is to read a configuration file for a program). The file is loaded and compiled, then executed, effectively putting any assignments it does into the Lua script space.
My example Lua file is this:
a = 22
b = 33
c = "nick"
-- do tests if wanted
if a < b then
a = 99
end -- if
The advantage of using Lua is that you can do tests or arithmetic inside the configuration file (and put comments).
Here is the code to read it in. We also extract a couple of values from the Lua script space back into C space:
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include "lua.h"
void error (lua_State *L, const char *fmt, ...)
{
va_list argp;
va_start (argp, fmt);
vfprintf (stderr, fmt, argp);
va_end (argp);
lua_close (L);
exit (1);
} /* end of error function */
int main (void)
{
int a, b;
const char * c;
lua_State * L = lua_open(); /* opens Lua */
luaopen_base(L); /* opens the basic library */
if (luaL_loadfile(L, "myconfig.lua") ||
lua_pcall (L, 0, 0, 0))
error (L, "Error loading file: %s", lua_tostring (L, -1));
/* get value of "a" */
lua_getglobal (L, "a");
if (!lua_isnumber (L, -1))
error (L, "'a' should be a number\n");
a = (int) lua_tonumber (L, -1);
printf ("Found value of 'a' to be %i\n", a);
lua_pop (L, 1);
/* get value of "c" */
lua_getglobal (L, "c");
if (!lua_isstring (L, -1))
error (L, "'c' should be a string\n");
c = lua_tostring (L, -1);
printf ("Found value of 'c' to be %s\n", c);
lua_pop (L, 1);
lua_close (L);
return 0;
} /* end of main */
This example also uses a more elaborate error function (suggested from the Lua book). This error function reports the error and terminates the application, however you may find it more useful to report the error to the user and continue processing. |
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|