LUA Programming

All

Intro

Hey boy, just use this Lua script and everything will be ok on your game. It’s all embedded!

Lua

An interesting tutorial about Lua embedded is [1]. So cool to learn about embedding Lua in C and C++. The code below, from the same source, is so simple and prints:

The average is  30
The sum is      150
#include <stdio.h>

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

/* the Lua interpreter */
lua_State* L;

/* The function we'll call from the lua script */
static int average(lua_State *L)
{
        /* get number of arguments */
        int n = lua_gettop(L);
        double sum = 0;
        int i;

        /* loop through each argument */
        for (i = 1; i <= n; i++)
        {
                if (!lua_isnumber(L, i)) 
                {
                      lua_pushstring(L, "Incorrect argument to 'average'");
                      lua_error(L);
                }

                /* total the arguments */
                sum += lua_tonumber(L, i);
        }

        /* push the average */
        lua_pushnumber(L, sum / n);

        /* push the sum */
        lua_pushnumber(L, sum);

        /* return the number of results */
        return 2;
}


int main ( int argc, char *argv[] )
{
        /* initialize Lua */
        L = lua_open();

        /* load Lua base libraries */
        lua_baselibopen(L);

        /* register our function */
        lua_register(L, "average", average);

        /* run the script */
        lua_dofile(L, "average.lua");

        /* cleanup Lua */
        lua_close(L);

        return 0;
}

REFs

[1] https://debian-administration.org/article/264/Embedding_a_scripting_language_inside_your_C/C_code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s