gnu readline: How to keep a history list of entered command lines

When I was assigned a project to create a text console based simulator, I am looking into how to keep a history list of entered command lines like Bash Shell. Users are allow to search through the history list by hitting UP and DOWN arrow key.

GNU readline library provides this feature, and it is pretty easy to use. Lets look at the example below:

// simple_rl.cpp
#include <stdio.h>
#include <stdlib.h>

#include <readline/readline.h>
#include <readline/history.h>


int main()
{
    char *buf;

    rl_bind_key('\t',rl_abort);//disable auto-complete

    while((buf = readline("\n >> "))!=NULL)
    {
        if (strcmp(buf,"quit")==0)
            break;

        printf("[%s]\n",buf);

        if (buf[0]!=0)
            add_history(buf);
    }

    free(buf);

    return 0;
}

I use rl_bind_key() to disable the tab key for file auto-complete that enabled by default. I will write another post for custom auto-complete using libreadline soon. add_history() is used to add the enterd inputs into the history list, and key bindings to arrow keys are enabled by default.

Compile it with g++ now:

g++ -o simple_rl{,.cpp} -lreadline

That is it, simple and nice 🙂

STL Singleton Template

Singleton is one of my favorite design pattern, I use it to keep a global information for my application such as Configurations, Logger etc. I remember I wrote a post regarding simple singleton class, which it does not really work as singleton. It is just a silly way to make a object class looks like singleton.

Lately I’ll been using STL Singleton template for my projects, I find it simple to implement and yet efficient.

Continue reading

How to embed Lua 5.1 in C++

Lua, is a scripting language providing dynamic data structures, maths, io and string manipulations just like any interprete language such as Bash, Python, Ruby etc.

What is so special about Lua?
Lua is Fast, Light-weight and Embeddable.

Lua can be embedded into c and c++ programs and Lua core are statically complied with your c++ programs, meaning your c++ program itself are now becoming Lua interpreter that execute Lua scripts. To extend your c++ application to execute Lua script is simple, lets check it out.

Continue reading