Calling Lua scripts from c++’s example was written in post How to embed Lua 5.1 in C++. Now, let us look at how to access Lua’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 is very important keep in mind while coding with C API of Lua.
P.S: I am using Lua 5.1.3’s C API.
This is an interesting quest given by my friend who working in Intel, during our conversation online.
How to swap two variables ?
Let say A=123 and B=546, how to swap them. So this is a quest, be smart enough not to give a plain solution like create a temporary variable to swap them. First of all my answer sounds a bit stupid. I say if I coded in python,
Okay that is not the expecting answer. Before you look at the solution below, maybe you would like to try to figure out.
Hint: use logic XOR, no additional variable is needed.
A=A XOR B;
B=A XOR B;
A=A XOR B;
XOR is known as exclusive disjunction where the nature of XOR is when 1 XOR 0 will equal to 1 but when 1 XOR 1 will becomes 0. Another important behavior of XOR is when (a XOR b) XOR b will resulting a.
So lets look back at the solution, you will find A XOR B seems to become “something else”, where this “something else” will return A if we XOR B and return B if we XOR A. So first line, A=(A XOR B). Secondly B = (A XOR B) XOR B = A, where we replace the original A into (A XOR B). Last line, A= ( A XOR B) XOR A = B. Seems at second line B already become A, so we replace B as A.
Interesting isn’t it? Look at it few times, if you can’t get it.