<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	>

<channel>
	<title>c/c++ linux programming by examples</title>
	<atom:link href="http://cc.byexamples.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://cc.byexamples.com</link>
	<description>c/c++ linux programming tips and techniques with simple examples</description>
	<pubDate>Tue, 22 Jul 2008 15:16:07 +0000</pubDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
			<item>
		<title>Calling Lua function from C++</title>
		<link>http://cc.byexamples.com/20080715/calling-lua-function-from-c/</link>
		<comments>http://cc.byexamples.com/20080715/calling-lua-function-from-c/#comments</comments>
		<pubDate>Tue, 15 Jul 2008 13:28:26 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Lua]]></category>

		<category><![CDATA[c]]></category>

		<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/?p=44</guid>
		<description><![CDATA[Calling Lua function from c++ is very simple. Value passing between c++ and Lua goes through stack, Lua C API provides a convenience ways for you to call Lua function from C. To call Lua function, you need to specify:
1. Function Name.
2. Parameters of function call.
3. Return values expected ( Lua function support multiple results [...]]]></description>
			<content:encoded><![CDATA[<p>Calling Lua function from c++ is very simple. Value passing between c++ and Lua goes through stack, Lua C API provides a convenience ways for you to call Lua function from C. To call Lua function, you need to specify:</p>
<p>1. Function Name.<br />
2. Parameters of function call.<br />
3. Return values expected ( Lua function support multiple results reture)</p>
<p>Let say my lua function name call f in last.lua, takes 2 parameters. </p>
<pre><code>-- last.lua
function f (x, y)
    return (x^2 * math.sin(y))/(1 - x)
end</code></pre>
<p>I perform function call from c++ like this:</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">
//last.cc
# extern "C" {  
# #include "lua.h"  
# #include "lualib.h"  
# #include "lauxlib.h"  
# }  

int main()
{
    double z;
    lua_State *L = lua_open();
    luaL_openlibs(L);
    if (luaL_loadfile(L, "last.lua") || lua_pcall(L, 0, 0, 0)) {
        printf("error: %s", lua_tostring(L, -1));
        return -1;
    }

    lua_getglobal(L, "f");
    if(!lua_isfunction(L,-1))
    {
        lua_pop(L,1);
        return -1;
    }
    lua_pushnumber(L, 21);   /* push 1st argument */
    lua_pushnumber(L, 31);   /* push 2nd argument */

    /* do the call (2 arguments, 1 result) */
    if (lua_pcall(L, 2, 1, 0) != 0) {
        printf("error running function `f': %s\n",lua_tostring(L, -1));
        return -1;
    }

    /* retrieve result */
    if (!lua_isnumber(L, -1)) {
        printf("function `f' must return a number\n");
        return -1;
    }
    z = lua_tonumber(L, -1);
    printf("Result: %f\n",z);
    lua_pop(L, 1);
    lua_close(L);

    return 0;
}</textarea>
<p>Compile it with g++ like this:</p>
<pre><code>g++ -o last{,.cc} -llua -ldl</code></pre>
<p>The results:</p>
<pre><code>Result: -12.158958</code></pre>
<p>Brief explanation of the C++ codes above:<br />
First, I trigger <em>lua_getglobal</em> to get the function name, then I push 2 parameters to stack. I make lua_pcall by telling Lua I have 2 params and expect 1 value return. Upon success, I retrieve the return value from the top of the stack.
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080706/calling-c-function-from-lua-implement-sleep-function/" rel="bookmark" title="Permanent Link: calling c++ function from Lua, implement sleep function" >calling c++ function from Lua, implement sleep function</a></span>
<div class="aizatto_related_posts_excerpt">You can&#8217;t call c function directly from Lua, you have to create a wrapper function that allows calling from Lua. In this&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080621/accessing-lua-global-variables-from-c/" rel="bookmark" title="Permanent Link: Accessing Lua global variables from c++" >Accessing Lua global variables from c++</a></span>
<div class="aizatto_related_posts_excerpt">Calling Lua scripts from c++&#8217;s example was written in post How to embed Lua 5.1 in C++. Now, let us look at how to acces&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080607/how-to-embed-lua-51-in-c/" rel="bookmark" title="Permanent Link: How to embed Lua 5.1 in C++" >How to embed Lua 5.1 in C++</a></span>
<div class="aizatto_related_posts_excerpt">Lua, is a scripting language providing dynamic data structures, maths, io and string manipulations just like any interpr&#8230;</div>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20080715/calling-lua-function-from-c/feed/</wfw:commentRss>
		</item>
		<item>
		<title>calling c++ function from Lua, implement sleep function</title>
		<link>http://cc.byexamples.com/20080706/calling-c-function-from-lua-implement-sleep-function/</link>
		<comments>http://cc.byexamples.com/20080706/calling-c-function-from-lua-implement-sleep-function/#comments</comments>
		<pubDate>Sun, 06 Jul 2008 05:38:58 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Lua]]></category>

		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/?p=43</guid>
		<description><![CDATA[You can&#8217;t call c function directly from Lua, you have to create a wrapper function that allows calling from Lua. In this post, shows a simple example to implement millisecond sleep function to Lua using nanosleep. 
To allow function call from Lua script, your function must obey certain format. As variable passing from Lua to [...]]]></description>
			<content:encoded><![CDATA[<p>You can&#8217;t call c function directly from Lua, you have to create a wrapper function that allows calling from Lua. In this post, shows a simple example to implement millisecond sleep function to Lua using nanosleep. </p>
<p>To allow function call from Lua script, your function must obey certain format. As variable passing from Lua to C and vice versa are through Lua Stack, therefore, the wrapper function must pass Lua State as the only parameter.<br />
<strong>How about the real function call parameters?</strong> We can get it from the stack using lua_tonumber(), lua_tostring() etc. To return result of function call, we use lua_pushnumber(), lua_pushstring() etc. Because Lua function allows return more than 1 results, therefore you need tell Lua by returning an integer value.</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">
    static int Function_Name (lua_State *L) {
      int i = lua_tointeger(L, 1);  /* get argument */
      /* carry on the procedures here ... */
      lua_pushinteger(L, sin(d));  /* push result */
      return 1;  /* number of results */
    }
</textarea>
<p>We need to setup a library to contain your functions. By doing this, construct a static structure in array. Next, we load up our lib by calling  luaL_openlib() and at last, to trigger a dofile().</p>
<p>Lets check out the sample codes on how to implement msleep function to Lua.</p>
<p><span id="more-43"></span></p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

#include<time.h>

int L_MSleep(lua_State* l)
{
    int milisec=0;
    struct timespec req={0};
    time_t sec;

    milisec=luaL_optint(l,1,0); // obtain parameter

    if (milisec==0)
       return 0;

    sec=(int)(milisec/1000);

    milisec=milisec-(sec*1000);
    req.tv_sec=sec;
    req.tv_nsec=milisec*1000000L;

    while(nanosleep(&#038;req,&#038;req)==-1)
         continue;

    return 1;
}

int main()
{

    const static struct luaL_reg misc [] = {  
        {"msleep", &#038;L_MSleep},
        {NULL,NULL} //must!
    };

    lua_State *L = lua_open();
    luaL_openlibs(L);
    //open your lib
    luaL_openlib(L, "misc", misc, 0);

    if (luaL_loadfile(L, "callc.lua") || lua_pcall(L, 0, 0, 0))
        printf("error: %s", lua_tostring(L, -1));
    
    lua_close(L);

    return 0;
}
</textarea>
<p>From the example above, we implemented msleep() that takes only 1 parameter, and we created a library &#8220;misc&#8221; in Lua. luaL_optint() is actually a clean version of doing lua_isinteger() and lua_tointeger().  luaL_optint() takes 3 parameter, </p>
<pre><code> luaL_optint(<strong>Lua State</strong>, <strong>Stack Number</strong>, <strong>Default Value</strong>)</code></pre>
<p>If the param specified by lua function call is not integer, the default value will be assigned.</p>
<p>So let see how we can call that from Lua script.</p>
<pre><code>
for i=1,9,1 do
    io.write(string.format("[%d] Hello\n",i))
    misc.msleep(1000) -- sleep 1 sec
end
</code></pre>
<p>Check out for more details from Programming in Lua Chapter 26 [1].</p>
<p>And more Lua examples here, <a href="http://cc.byexamples.com/category/lua/">http://cc.byexamples.com/category/lua/</a>.</p>
<p>Reference:<br />
[1] <a href="http://www.lua.org/pil/26.html">Programming In Lua, Chapter 26 #Calling C from Lua</a>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070525/nanosleep-is-better-than-sleep-and-usleep/" rel="bookmark" title="Permanent Link: nanosleep is better than sleep and usleep" >nanosleep is better than sleep and usleep</a></span>
<div class="aizatto_related_posts_excerpt">Don&#8217;t know whether you aware of the example code at Tap the interrupt signal, I am using sleep(1) within endless loop at&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070520/tap-the-interrupt-signal/" rel="bookmark" title="Permanent Link: Tap the interrupt signal" >Tap the interrupt signal</a></span>
<div class="aizatto_related_posts_excerpt">When you hit control+c, you are actually send a SIGINT ( Interrupt signal ) to your program. By default, your program wi&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080616/gnu-readline-implement-custom-auto-complete/" rel="bookmark" title="Permanent Link: GNU readline: Implement Custom Auto-complete" >GNU readline: Implement Custom Auto-complete</a></span>
<div class="aizatto_related_posts_excerpt">GNU readline implement filename auto-complete by default, it will list all the files in the current directory. We can di&#8230;</div>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20080706/calling-c-function-from-lua-implement-sleep-function/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Accessing Lua global variables from c++</title>
		<link>http://cc.byexamples.com/20080621/accessing-lua-global-variables-from-c/</link>
		<comments>http://cc.byexamples.com/20080621/accessing-lua-global-variables-from-c/#comments</comments>
		<pubDate>Fri, 20 Jun 2008 19:09:45 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Lua]]></category>

		<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/?p=42</guid>
		<description><![CDATA[Calling Lua scripts from c++&#8217;s example was written in post How to embed Lua 5.1 in C++. Now, let us look at how to access Lua&#8217;s global variables from c++.
Value passing between c++ and Lua rely on Lua stack. Stack is a data structure based on the principle of Last In First Out (LIFO). This [...]]]></description>
			<content:encoded><![CDATA[<p>Calling Lua scripts from c++&#8217;s example was written in post <a href="http://cc.byexamples.com/20080607/how-to-embed-lua-51-in-c/">How to embed Lua 5.1 in C++</a>. Now, let us look at how to access Lua&#8217;s global variables from c++.</p>
<p>Value passing between c++ and Lua rely on Lua stack. <a href="http://en.wikipedia.org/wiki/Stack_(data_structure)">Stack</a> is a data structure based on the principle of Last In First Out <strong>(LIFO)</strong>. This is very important keep in mind while coding with C API of Lua.</p>
<p>P.S: I am using Lua 5.1.3&#8217;s C API.</p>
<p><span id="more-42"></span></p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">
//aconf.cpp
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

int main()
{
    int var1=0,var2=0;

    lua_State *L = lua_open();
    luaL_openlibs(L);
    if (luaL_loadfile(L, "config.lua") || lua_pcall(L, 0, 0, 0))
    {
        printf("error: %s", lua_tostring(L, -1));
        return -1;
    }

    lua_getglobal(L, "var1");
    lua_getglobal(L, "var2");
    if (!lua_isnumber(L, -2)) {
        printf ("`var1' should be a number\n");
        return -1;
    }
    if (!lua_isnumber(L, -1))
    {
        printf("`var2 should be a number\n");
        return -1;
    }
    var1 = (int)lua_tonumber(L, -2);
    var2 = (int)lua_tonumber(L, -1);
    printf("var1: %d\nvar2: %d\n",var1, var2);
    lua_close(L);

    return 0;
}
</textarea>
<p>The Lua script &#8220;config.lua&#8221;:</p>
<pre><code>var1=12
var2=34</code></pre>
<p>Compilation line:</p>
<pre><code>g++ -o aconf{,.cpp} -llua -ldl</code></pre>
<p><code>if (luaL_loadfile(L, "config.lua") || lua_pcall(L, 0, 0, 0))</code> can be written as <code>luaL_dofile(L,"config.lua")</code>, it does the same thing. By calling <code> lua_getglobal(L, "var1");</code>, Lua will push the value of var1 to the stack. When execute getglobal for &#8220;var2&#8243;, again it will push var2&#8217;s value to the stack, var2 will now stack on top of var1.</p>
<p>The most top of the stack will be assign as  logical address -1. Stack address -2 will be at below the stack -1. Therefore to access var1, you have to point to -2. For more info regarding Lua stack, can read <a href="http://www.lua.org/pil/24.2.html">HERE</a>.</p>
<p>To check the value type in the stack -2 (var1) is it number, we can use this:<br />
<code>lua_isnumber(L, -2)</code></p>
<p>To access the value to number, we do this:<br />
<code>lua_tonumber(L, -2)</code></p>
<p>As <code>lua_tonumber(L, -2)</code> will return as double, therefore we must add (int) in front of the function call. Well, we should use <code>lua_tointeger(L, -2)</code> in this case.</p>
<p>Again, I can access var1 and var2 one by one, therefore you access both variables from the top stack.</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">lua_getglobal(L, "var1");
var1=lua_tointeger(L,-1);
lua_getglobal(L, "var2");
var2=lua_tointeger(L,-1);
</textarea>
<p>When accessing Lua script and trigger exception, the error message will always push to the stack, that why We can print out the message when errors detected like this:</p>
<pre><code>printf("error: %s", lua_tostring(L, -1));</code></pre>
<p>Accessing simple variables is simple, but for accessing table data type, you need more steps, the Lua online ebook does cover that.</p>
<p>Lua Online Ebook: <a href="http://www.lua.org/pil/index.html">Programming in Lua</a>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070118/extern-variable-define-else-where-2/" rel="bookmark" title="Permanent Link: extern, variable define else where" >extern, variable define else where</a></span>
<div class="aizatto_related_posts_excerpt">Sometimes we might need to declare global variable. Let say I have 5 files (cat.c, dog.c, tiger.c, rabbit.c and animal.c&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080609/stl-singleton-template/" rel="bookmark" title="Permanent Link: STL Singleton Template" >STL Singleton Template</a></span>
<div class="aizatto_related_posts_excerpt">Singleton is one of my favorite design pattern, I use it to keep a global information for my application such as Configu&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070118/print-line-help-for-debug/" rel="bookmark" title="Permanent Link: print line help for debug" >print line help for debug</a></span>
<div class="aizatto_related_posts_excerpt">The simplest debug technique is to print out a line contains the required variables value. By printing out a line at a s&#8230;</div>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20080621/accessing-lua-global-variables-from-c/feed/</wfw:commentRss>
		</item>
		<item>
		<title>GNU readline: Implement Custom Auto-complete</title>
		<link>http://cc.byexamples.com/20080616/gnu-readline-implement-custom-auto-complete/</link>
		<comments>http://cc.byexamples.com/20080616/gnu-readline-implement-custom-auto-complete/#comments</comments>
		<pubDate>Sun, 15 Jun 2008 17:55:04 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[add_history]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[readline]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/?p=41</guid>
		<description><![CDATA[GNU readline implement filename auto-complete by default, it will list all the files in the current directory. We can disable it by binds our TAB key to some other operation. In previous post, I simply abort the operation to ignore users hitting TABs.
Auto-complete are useful if only we can customize it. Well, readline allows us [...]]]></description>
			<content:encoded><![CDATA[<p>GNU readline implement filename auto-complete by default, it will list all the files in the current directory. We can disable it by binds our TAB key to some other operation. In <a href="http://cc.byexamples.com/20080613/gnu-readline-how-to-keep-a-history-list-of-entered-command-lines/">previous post</a>, I simply abort the operation to ignore users hitting TABs.</p>
<p>Auto-complete are useful if only we can customize it. Well, readline allows us do it by assign our own callback functions. First of all, you may want to read up the manual from <a href="http://www.math.utah.edu/docs/info/rlman_2.html#SEC36">HERE</a>. It does provides a c sample codes as well but I find it too complicated, here I provide a simplified version that can be compiled under c++.</p>
<p> <span id="more-41"></span></p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>

static char** my_completion(const char*, int ,int);
char* my_generator(const char*,int);
char * dupstr (char*);
void *xmalloc (int);

char* cmd [] ={ "hello", "world", "hell" ,"word", "quit", " " };

int main()
{
    char *buf;

    rl_attempted_completion_function = my_completion;

    while((buf = readline("\n &gt;&gt; "))!=NULL) {
        //enable auto-complete
        rl_bind_key('\t',rl_complete);

        printf("cmd [%s]\n",buf);
        if (strcmp(buf,"quit")==0)
            break;
        if (buf[0]!=0)
            add_history(buf);
    }

    free(buf);

    return 0;
}


static char** my_completion( const char * text , int start,  int end)
{
    char **matches;

    matches = (char **)NULL;

    if (start == 0)
        matches = rl_completion_matches ((char*)text, &#038;my_generator);
    else
        rl_bind_key('\t',rl_abort);

    return (matches);

}

char* my_generator(const char* text, int state)
{
    static int list_index, len;
    char *name;

    if (!state) {
        list_index = 0;
        len = strlen (text);
    }
  
    while (name = cmd[list_index]) {
        list_index++;

        if (strncmp (name, text, len) == 0)
            return (dupstr(name));
    }

    /* If no names matched, then return NULL. */
    return ((char *)NULL);

}

char * dupstr (char* s) {
  char *r;

  r = (char*) xmalloc ((strlen (s) + 1));
  strcpy (r, s);
  return (r);
}

void * xmalloc (int size)
{
    void *buf;

    buf = malloc (size);
    if (!buf) {
        fprintf (stderr, "Error: Out of memory. Exiting.'n");
        exit (1);
    }

    return buf;
}
</textarea>
<p>I store my &#8216;keywords&#8217; targeted for auto-completion in an array <b>cmd</b>. Before calling readline(), I must point my completion callback function to <b>rl_attempted_completion_function</b>. </p>
<p>In my_completion(), if the state==1 meaning auto-completing the first word from readline(). If the state &gt; 1 and my_completion() return NULL, filename auto-complete will be trigger automatically, which I find it damn irritating. So when state !=1, I disable it, and enable it back after next readline(). It is a dirty hack to me, I am still searching for a proper way to disable filename completion entirely.</p>
<p>I wrote xmalloc() myself because extern xmalloc doesn&#8217;t seems to work while compiling under c++.</p>
<p>To get better understanding of readline auto-complete, please read up <a href="http://www.math.utah.edu/docs/info/rlman_2.html#SEC36">the manual</a> carefully and try it out yourself.</p>
<p>At last, hope you enjoy the post.
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080613/gnu-readline-how-to-keep-a-history-list-of-entered-command-lines/" rel="bookmark" title="Permanent Link: gnu readline: How to keep a history list of entered command lines" >gnu readline: How to keep a history list of entered command lines</a></span>
<div class="aizatto_related_posts_excerpt">When I was assigned a project to create a text console based simulator, I am looking into how to keep a history list of &#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080706/calling-c-function-from-lua-implement-sleep-function/" rel="bookmark" title="Permanent Link: calling c++ function from Lua, implement sleep function" >calling c++ function from Lua, implement sleep function</a></span>
<div class="aizatto_related_posts_excerpt">You can&#8217;t call c function directly from Lua, you have to create a wrapper function that allows calling from Lua. In this&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20071011/simple-callback-function/" rel="bookmark" title="Permanent Link: simple callback function" >simple callback function</a></span>
<div class="aizatto_related_posts_excerpt">Callback function is hard to trace, but sometimes it is very useful. Especially when you are designing libraries. Callba&#8230;</div>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20080616/gnu-readline-implement-custom-auto-complete/feed/</wfw:commentRss>
		</item>
		<item>
		<title>gnu readline: How to keep a history list of entered command lines</title>
		<link>http://cc.byexamples.com/20080613/gnu-readline-how-to-keep-a-history-list-of-entered-command-lines/</link>
		<comments>http://cc.byexamples.com/20080613/gnu-readline-how-to-keep-a-history-list-of-entered-command-lines/#comments</comments>
		<pubDate>Fri, 13 Jun 2008 15:26:36 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[add_history]]></category>

		<category><![CDATA[c]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[readline]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/?p=40</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>GNU readline library provides this feature, and it is pretty easy to use. Lets look at the example below:</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">// 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;
}</textarea>
<p>I use <strong>rl_bind_key()</strong> 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. <strong>add_history()</strong> is used to add the enterd inputs into the history list, and key bindings to arrow keys are enabled by default.</p>
<p>Compile it with g++ now:</p>
<pre><code>g++ -o simple_rl{,.cpp} -lreadline</code></pre>
<p>That is it, simple and nice :)
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080616/gnu-readline-implement-custom-auto-complete/" rel="bookmark" title="Permanent Link: GNU readline: Implement Custom Auto-complete" >GNU readline: Implement Custom Auto-complete</a></span>
<div class="aizatto_related_posts_excerpt">GNU readline implement filename auto-complete by default, it will list all the files in the current directory. We can di&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070122/creating-command-line-parser/" rel="bookmark" title="Permanent Link: creating command-line parser" >creating command-line parser</a></span>
<div class="aizatto_related_posts_excerpt">Notice that almost all linux programs have command-line options, you can pass in the arguments to your programs. Some co&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070118/sscanf-scan-input-from-a-string-2/" rel="bookmark" title="Permanent Link: sscanf, scan input from a string" >sscanf, scan input from a string</a></span>
<div class="aizatto_related_posts_excerpt">In order to store a particular value to variable from a string, we can use sscanf.</p>
<p>Definition:<br />
int sscanf(const char&#8230;</p></div>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20080613/gnu-readline-how-to-keep-a-history-list-of-entered-command-lines/feed/</wfw:commentRss>
		</item>
		<item>
		<title>STL Singleton Template</title>
		<link>http://cc.byexamples.com/20080609/stl-singleton-template/</link>
		<comments>http://cc.byexamples.com/20080609/stl-singleton-template/#comments</comments>
		<pubDate>Sun, 08 Jun 2008 23:30:57 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[c++]]></category>

		<category><![CDATA[design pattern]]></category>

		<category><![CDATA[c++ templates]]></category>

		<category><![CDATA[singleton]]></category>

		<category><![CDATA[STL]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/?p=39</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <a href="http://cc.byexamples.com/20070526/simple-singleton-class/">simple singleton class</a>, which it does not really work as singleton. It is just a silly way to make a object class looks like singleton.</p>
<p>Lately I&#8217;ll been using STL Singleton template for my projects, I find it simple to implement and yet efficient.</p>
<p><span id="more-39"></span></p>
<p>Lets define the Singleton Template:</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">template<typename T>

class CSingleton
{
    public:
        static T&#038; Instance()
        {
            static T me;
            return me;
        }
};</textarea>
<p>In order to turn your own class into singleton, you class must inherits from CSingleton like this:</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">class MyClass: public CSingleton<MyClass>
{
    public:
        MyClass(){};
        ~MyClass(){};
        void Print() { printf("testing %d\n",val); }
        int val;
};
</textarea>
<p>Access MyClass variables and functions like this:</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">int main(void)
{
   MyClass::Instance().val=7;
   MyClass::Instance().Print();
   
   return 0;
}</textarea>
<p>I find the appearance of <strong>MyClass::Instance()</strong> are ugyl and lengthy, therefore I like to define a nicer look of singleton class.</p>
<pre><code>#define MYCLASS MyClass::Instance()</code></pre>
<p>So my source code looks cleaner. </p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">int main(void)
{
   MYCLASS.val=7;
   MYCLASS.Print();
   
   return 0;
}</textarea>
<p>Anyway, this is just my preference. Enjoy yourself with STL Singleton Template.
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070526/simple-singleton-class/" rel="bookmark" title="Permanent Link: simple singleton class" >simple singleton class</a></span>
<div class="aizatto_related_posts_excerpt">Singleton is one of the common design pattern used to make a class object exist only one instant. I have read some books&#8230;</div>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20080609/stl-singleton-template/feed/</wfw:commentRss>
		</item>
		<item>
		<title>How to embed Lua 5.1 in C++</title>
		<link>http://cc.byexamples.com/20080607/how-to-embed-lua-51-in-c/</link>
		<comments>http://cc.byexamples.com/20080607/how-to-embed-lua-51-in-c/#comments</comments>
		<pubDate>Sat, 07 Jun 2008 14:13:48 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Lua]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/?p=38</guid>
		<description><![CDATA[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, [...]]]></description>
			<content:encoded><![CDATA[<p>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. </p>
<p><b>What is so special about Lua? </b><br />
Lua is Fast, Light-weight and Embeddable.</p>
<p>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.</p>
<p><span id="more-38"></span><br />
Before you start, please download and install Lua from <a href="http://www.lua.org/">HERE</a>.<br />
Disclaimer: My example are based on Lua 5.1.3.</p>
<p><b>1. Create a simple Lua script and name it as foo.lua.</b></p>
<pre><code>io.write("Please enter your name: ")
name = io.read() -- read input from user
print ("Hi " .. name .. ", enjoy hacking with Lua");</code></pre>
<p><b>2. Write a cpp program clua.cpp to execute foo.lua.</b></p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

int main()
{
    int s=0;

    lua_State *L = lua_open();

    // load the libs
    luaL_openlibs(L);

    //run a Lua scrip here
    luaL_dofile(L,"foo.lua");

    printf("\nI am done with Lua in C++.\n");

    lua_close(L);

    return 0;
}</textarea>
<p>Lua API are in c format, in order to make it work with C++ you need to extern &#8220;C&#8221;. luaL_openlibs(L) loading up all the basic libs such as IO, String, Math etc. I believe if you are using Lua 5.0, you have to replace luaL_open(L) to load the libs one by one like this:</p>
<pre><code>      luaopen_base(L);
      luaopen_table(L);
      luaopen_io(L);
      luaopen_string(L);
      luaopen_math(L);</code></pre>
<p><b>3. Compile the clua.cpp with g++.</b></p>
<pre><code>g++ -o clua{,.cpp} -llua -ldl</code></pre>
<p><b>IMPORTANT!</b> You need to link you program with libdl besides liblua. I believe the use of luaL_openlibs() are calling dlopen, dlclose, dlerror, dlsym which needs libdl.</p>
<p>Else you may get linking error like this:</p>
<pre><code>/usr/local/lib/liblua.a(loadlib.o): In function `ll_loadfunc':
loadlib.c:(.text+0x917): undefined reference to `dlsym'
loadlib.c:(.text+0x924): undefined reference to `dlerror'
loadlib.c:(.text+0x9fc): undefined reference to `dlopen'
loadlib.c:(.text+0xa11): undefined reference to `dlerror'
/usr/local/lib/liblua.a(loadlib.o): In function `gctm':
loadlib.c:(.text+0x101e): undefined reference to `dlclose'
collect2: ld returned 1 exit status
</code></pre>
<p><b>4. Execute your c++ app</b></p>
<pre><code>$ ./clua
Please enter your name: surface
Hi surface, enjoy hacking with Lua

I am done with Lua in C++.
</code></pre>
<p>Cool isn&#8217;t it? </p>
<p>Lets try to change foo.lua into this:</p>
<pre><code>io.write("Please enter your name: ")
name = io.read()
io.write("Hi " .. string.format("\27\91\1;38;40m%s\27\91\0;47;40m",name) .. ", enjoy hacking with Lua\n");</code></pre>
<p>Now, run <b>./clua</b> again! You name will be in RED, check out text color example <a href="http://linux.byexamples.com/archives/184/print-text-in-colors-with-a-simple-command-line/">HERE</a></p>
<p>Ofcause, in order to really extend your c++ apps to Lua script, you need more than lua_dofile(), you need to allow Lua script calling your c++ functions, you may need to access variables from Lua to c++ and vice versa. Well, mean while I am still learning, I will share more when I learn more tricks! </p>
<p><b>Reference and Tutorial!</b><br />
Lua provides excellent documentation: </p>
<li><a href="http://www.lua.org/manual/5.1/">1. Lua Reference Manual</a></li>
<li><a href="http://www.inf.puc-rio.br/~roberto/pil2/">2. Ebook: Programming in Lua</a></li>
<p>I am dilemma here whether should I post this at <a href="http://linux.byexamples.com">http://linux.byexamples.com</a> or <a href="http://cc.byexamples.com">http://cc.byexamples.com</a>. As an introduction post for Lua programming, I will put it on both blogs. For future post, if I write about Lua scripting, I will post at <a href="http://linux.byexamples.com">http://linux.byexamples.com</a> and if I write about Lua C++ API, it will be at <a href="http://cc.byexamples.com">http://cc.byexamples.com</a>.</p>
<p>Hope you enjoy this post, and start to script with Lua.<br />
@lightstar: In case you are reading this, I would like to say thank you for introduce this wonderful language to me, I enjoy it very much!
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080621/accessing-lua-global-variables-from-c/" rel="bookmark" title="Permanent Link: Accessing Lua global variables from c++" >Accessing Lua global variables from c++</a></span>
<div class="aizatto_related_posts_excerpt">Calling Lua scripts from c++&#8217;s example was written in post How to embed Lua 5.1 in C++. Now, let us look at how to acces&#8230;</div>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20080607/how-to-embed-lua-51-in-c/feed/</wfw:commentRss>
		</item>
		<item>
		<title>simple callback function</title>
		<link>http://cc.byexamples.com/20071011/simple-callback-function/</link>
		<comments>http://cc.byexamples.com/20071011/simple-callback-function/#comments</comments>
		<pubDate>Thu, 11 Oct 2007 14:30:23 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[fprintf]]></category>

		<category><![CDATA[function pointer]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/20071011/simple-callback-function/</guid>
		<description><![CDATA[Callback function is hard to trace, but sometimes it is very useful. Especially when you are designing libraries. Callback function is like asking your user to gives you a function name, and you will call that function under certain condition.
For example, you write a callback timer. It allows you to specified the duration and what [...]]]></description>
			<content:encoded><![CDATA[<p>Callback function is hard to trace, but sometimes it is very useful. Especially when you are designing libraries. Callback function is like asking your user to gives you a function name, and you will call that function under certain condition.</p>
<p>For example, you write a callback timer. It allows you to specified the duration and what function to call, and the function will be callback accordingly. &#8220;Run myfunction() every 10 seconds for 5 times&#8221; </p>
<p>Or you can create a function directory, passing a list of function name and ask the library to callback accordingly. &#8220;Callback success() if success, callback fail() if failed.&#8221; </p>
<p>Lets look at a simple function pointer example</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">
void cbfunc()
{
    printf("called");
}

int main ()
{
     /* function pointer */
    void (*callback)(void);

    /* point to your callback function */
    callback=(void *)cbfunc;
    
   /* perform callback */
   callback();

   return 0;
}
</textarea>
<p><strong>How to pass argument to callback function?</strong><br />
Observered that function pointer to implement callback takes in void *, which indicates that it can takes in any type of variable including structure. Therefore you can pass in multiple arguments by structure. </p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">
typedef struct _myst
{
    int a;
    char b[10];
}myst;

void cbfunc(myst *mt)
{
    fprintf(stdout,"called %d %s.",mt->a,mt->b);
}

int main()
{

    /* func pointer */
    void (*callback)(void *);

    //param
    myst m;
    m.a=10;
    strcpy(m.b,"123");
    
    /* point to callback function */ 
    callback = (void*)cbfunc;
    
    /* perform callback and pass in the param */
    callback(&#038;m);

    return 0;

}
</textarea>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20080616/gnu-readline-implement-custom-auto-complete/" rel="bookmark" title="Permanent Link: GNU readline: Implement Custom Auto-complete" >GNU readline: Implement Custom Auto-complete</a></span>
<div class="aizatto_related_posts_excerpt">GNU readline implement filename auto-complete by default, it will list all the files in the current directory. We can di&#8230;</div>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20071011/simple-callback-function/feed/</wfw:commentRss>
		</item>
		<item>
		<title>libcurl - HTTP,ftp,ssh,telnet,ldap client API</title>
		<link>http://cc.byexamples.com/20071007/libcurl-httpftpsshtelnetldap-client-api/</link>
		<comments>http://cc.byexamples.com/20071007/libcurl-httpftpsshtelnetldap-client-api/#comments</comments>
		<pubDate>Sat, 06 Oct 2007 19:07:36 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[libcurl]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/20071007/libcurl-httpftpsshtelnetldap-client-api/</guid>
		<description><![CDATA[curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos&#8230;), file transfer resume, proxy tunneling and [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos&#8230;), file transfer resume, proxy tunneling and a busload of other useful tricks.</p>
<p>Quote from <a href="http://curl.haxx.se/">http://curl.haxx.se/</a>
</p></blockquote>
<p><strong>Advantages of using libcurl:</strong></p>
<li>curl is open source.</li>
<li>libcurl API support multiple bindings.</li>
<li>libcurl is cross platform that supports windows and *nix.</li>
<li>API doc of libcurl are easy to follow, it also provides source code examples.  </li>
<p>You do not need to read up RFC to code for HTTP post or ftp client, you just need to download libcurl-dev and try it out. </p>
<p>Let me show you one of the simple example source code from curl official site.</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">
/*****************************************************************************
 *                                  _   _ ____  _
 *  Project                     ___| | | |  _ \| |
 *                             / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                             \___|\___/|_| \_\_____|
 *
 * $Id: simple.c,v 1.6 2004/08/23 14:22:52 bagder Exp $
 */

#include &lt;stdio.h&gt;
#include &lt;curl/curl.h&gt;

int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se");
    res = curl_easy_perform(curl);

    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  return 0;
}
</textarea>
<p>Check out the <a href="http://curl.haxx.se/libcurl/c/libcurl-tutorial.html">libcurl tutorial</a> and the <a href="http://curl.haxx.se/libcurl/c/example.html">sample source codes</a>.</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" >No related posts</span>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20071007/libcurl-httpftpsshtelnetldap-client-api/feed/</wfw:commentRss>
		</item>
		<item>
		<title>create your own time stamp 2</title>
		<link>http://cc.byexamples.com/20070927/create-your-own-time-stamp-2/</link>
		<comments>http://cc.byexamples.com/20070927/create-your-own-time-stamp-2/#comments</comments>
		<pubDate>Wed, 26 Sep 2007 16:19:27 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[localtime]]></category>

		<category><![CDATA[strftime]]></category>

		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://cc.byexamples.com/20070927/create-your-own-time-stamp-2/</guid>
		<description><![CDATA[From my previous post, create your own time stamp, I have introduced a way to construct your own time stamp.
Recently I found a better way, and with this function, you can create a better time stamp, yet the way of construct the time stamp is far more simple compared to my previous post.

#include
#include


int main()
{
  [...]]]></description>
			<content:encoded><![CDATA[<p>From my previous post, <a href="http://cc.byexamples.com/20070126/create-your-own-time-stamp/">create your own time stamp</a>, I have introduced a way to construct your own time stamp.</p>
<p>Recently I found a better way, and with this function, you can create a better time stamp, yet the way of construct the time stamp is far more simple compared to my previous post.</p>
<textarea name="code" class="cpp:nocontrols" cols="100" rows="15">
#include<stdio.h>
#include<time.h>


int main()
{
    char timestamp[100];
    time_t mytime;
    struct tm *mytm;
    mytime=time(NULL);
    mytm=localtime(&#038;mytime);

    strftime(timestamp,sizeof timestamp,"%a, %d %b %Y %H:%M:%S %z",mytm);

    printf("%s\n",timestamp);

    return 0;
}
</textarea>
<p>Yes, that&#8217;s it, and the output is show as below:</p>
<pre><code>Wed, 26 Sep 2007 23:54:50 +0800</code></pre>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070126/create-your-own-time-stamp/" rel="bookmark" title="Permanent Link: create your own time stamp" >create your own time stamp</a></span>
<div class="aizatto_related_posts_excerpt">If you wanna create a time stamp that display date and time, you can simply uses asctime() and localtime(), time() and a&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070314/create-a-timer/" rel="bookmark" title="Permanent Link: create a timer" >create a timer</a></span>
<div class="aizatto_related_posts_excerpt">Sometimes, you need a timer function. For example, you wanna check some live status every 5 seconds. By using sleep() is&#8230;</div>
</p>
<p><span class="aizatto_related_posts_title" ><a href="http://cc.byexamples.com/20070123/writing-log-files-or-config-files-uses-fprintf/" rel="bookmark" title="Permanent Link: writing log files or config files uses fprintf" >writing log files or config files uses fprintf</a></span>
<div class="aizatto_related_posts_excerpt">To write formatted string to files, the easiest way is uses fprintf. It works exactly the same way like printf. </p>
<p>Fi&#8230;</p></div>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cc.byexamples.com/20070927/create-your-own-time-stamp-2/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
