Why push a duplicate key when adding to a table in Lua? - c++

I'm learning how to bind C++ objects to Lua with type checking from the book Programming Gems 6 (Chapter 4.2). For the type checking the userdata/string pairs are being stored in an environment table, with the code given how to do that:
void Binder::pushusertype(void* udata, const char* tname) {
lua_pushlightuserdata(L, udata); // push address
lua_pushvalue(L, -1); // duplicate address
lua_pushstring(L, tname); // push type name
lua_rawset(L, LUA_ENVIRONMENTINDEX); // envtable[address] = tname
}
Where the Binder class has a Lua State as an attribute, named "L"
As you can see the address is pushed twice. As this small piece of code is only given as an example it doesn't seem like a duplicate address pushed onto the stack would serve any purpose outside of this function, which leads me to believe there's a specific reason for it. So my question is, why would one do this?

You don't.
The lua_rawset will pop tname & the duplicate off the stack, but will leave the original userdata on the stack.
I'm not sure if its a typo (looks unlikely), I guess it might be needed later.
Don't know if there is some more in the book, that mentions this, but thats what the code will do.

This function does two things:
it pushes a lightuserdata object to the stack and it will be at lua stack position -1 when the function returns. It also updates the current function environment with the name tname stored at table key address (equal to udata). If the current function environment is the normal global environment, the equivalent Lua code would be:
local x = <udata as lightuserdata>
_G[x] = <tname>
One duplicate of x is used to do the _G[x] = ... thing, the other is left on the stack when the function returns (consistent with the name of the function that starts with push).

Related

How to initialize "RInside" instance in a function NOT main function, and call it multiple times without getting "R is already initialized"?

I would like to use RInside in a function that is NOT the main function in my c++ program. After debugging, I found out that the function works for the first round and I get the output as expected but when it is called for the second time my program stops and I get the error message "R is already initialized". Can anybody help me to have a workaround to overcome this issue?
please see below a simple example to clarify that.
I need to call mainR() function from a function(my_func) that is also NOT the main function.I am actually dealing with a bit complex program so my_func will be also called multiple times, which made initializing RInside useless..
Sorry, the code doesn't look realistic but I just wanted to simplify and clarify my question.
#include <RInside.h>
void mainR()
{
RInside R; // create an embedded R instance
R["txt"] = "Hello, world!\n"; // assign a char* (string) to 'txt'
R.parseEvalQ("cat(txt)"); // eval the init string, ignoring any returns
}
void my_func()
{
mainR();
mainR();
.
.
}
It would appear (I am not an expert on RInside) that an application must have no more than one RInside object created over the course of an application's lifetime. This corresponds to C++'s concept of "static storage duration". When a variable is defined in the main function, the difference between "automatic" (the default) and "static" duration is usually insignificant, but it is highly significant for a function called more than once.
Adding the keyword static indicates that a variable is to have static storage duration.
static RInside R; // create an embedded R instance
This has two effects on a variable defined inside a function. First, the object is not destroyed when the function ends. Second, the object is not re-initialized when the function is called again. (It is still initialized when the function is called the first time.) This avoids the error where R was initialized twice. However, it also comes with a caveat—the object retains state between function calls. One must assume that the RInside object might have been used earlier, even at the beginning of mainR().

How to get pointer to first arg of function?

I want to reflective call function with same arguments without manually coping params (for future this will be macro and this will be automatically).
UFUNCTION()
void PleaseRespawnMe(FName className)
{
uint64 _frame; // Here is stack pointer?
UFunction* func = GetController()->ServerCheatManager->FindFunction("PleaseRespawnMe"); // function with same name
void* startStack = (void*)(&_frame - func->ParmsSize); // Start stack is pointer to first variable minus params size?
GetController()->ServerCheatManager->ProcessEvent(func, startStack); // calling using pointer of first argument
}
But &_frame pointer is too far from &className. Is there solutions to get pointer of args using address of local variable?
P.S. This is Unreal Engine 4 framework (calling function by name is unreal reflection system).
I checked the codes by searching FindFunction( and found this: for (TFieldIterator<UProperty>, I think this is what you want.
I tested it with my UFUNCTION and the iterators run through the input parameters then the return value.
I suggest that to search for (TFieldIterator<UProperty> or for (TFieldIterator<UProperty> It(Function); to see the use cases, and note the property flags, which could help with filtering specific properties you are looking for.

LLVM: Access Global Variable from Function Pass

In learning the LLVM framework, I am trying to implement an 'optimization' pass that prints the name of each method at runtime when the method is called.
I read that global variables should only be created in a Module Pass, and I create the strings there (one per function), with
Constant* data = ConstantDataArray::getString(M.getContext(), F.getName());
GlobalVariable* gvar =
new GlobalVariable(M,
data->getType(),
true,
GlobalValue::ExternalLinkage,
data,
"fname_" + F.getName().str());
This works fine, insofar as the strings are laid out correctly in memory in the assembly file generated by the 'optimized' bitcode.
However, I have not found a way to insert calls to print these strings in the Function Pass.
I want to use
Value* string = F.getValueSymbolTable().lookup("fname_" + F.getName().str());
CallInst* call = builder.CreateCall(emitPutS(string, builder, &TLI));
but string comes back as NULL. Is there a better way to look up global variables from a function?
Figured it out:
Basic blocks have a getModule() method, and modules have a getGlobalVariable(StringRef Name) method.
Alternatively, IRBuilder:CreateGlobalStringPtr(...) can be called from the function pass, and the Value* returned can be passed to emitPutS(...) directly. The module pass was not necessary.
Note, CallInst* call = builder.CreateCall(emitPutS(string, builder, &TLI)); is incorrect. emitPutS(...) will create the call in the basic block already. The CreateCall is erroneous.

Is it more efficient to call functions or fill control if statements with local variables rather than directly nesting a function call?

In C++, does it produce a faster executable if you supply the data to be compared within the brackets of an if statement as the implicit result of a nested function instead of a separate local variable? In the same way, is it more efficient to provide an argument to a function as the result of a nested function called, again instead of a separate local variable?
What I mean is:
int comparison=0;
char *name=nullptr;
GetNameFromRegistry(queried_name); //Unillustrated function that retrieves a name
//entry from the Windows registry, dynamically
//allocates a sufficiently-sized chunk of memory
//to hold it and null-terminates the string.
comparison=strcmp(queried_name,"Fred");
if(comparison==0){
MessageBox(NULL,
"We have found Fred.",
"Name Search",
MB_OK | MB_ICONINFORMATION);
}
as opposed to:
char *queried_name=nullptr;
GetNameFromRegistry(queried_name); //Unillustrated function that retrieves a name
//entry from the Windows registry, dynamically
//allocates sufficiently-sized chunk of memory
//to hold it and null-terminates the string.
if(strcmp(queried_name, "Fred")==0){
MessageBox(NULL,
"We have found Fred.",
"Name Search",
MB_OK | MB_ICONINFORMATION);
}
Another example:
CData gp_data; //CData is a class that holds values, arrays and
//volatile/non-volatilve data for a windows application,
//saving those non-volatile values to the registry to be
//retrieved the next time it is launched.
SendMessage(dialog,
WM_SETICON,
reinterpret_cast<WPARAM>(ICON_SMALL),
reinterpret_cast<LPARAM>(gp_data->Get_Small_Application_Icon()));
as opposed to:
HICON small_icon=0;
CData gp_data; //CData is a class with holds values, arrays and volatile data for
//a windows application, saving non-volatile values to the registry
//to use the next time it is launched.
small_icon=gp_data->Get_Small_Application_Icon();
SendMessage(dialog,
WM_SETICON,
reinterpret_cast<WPARAM>(ICON_SMALL),
reinterpret_cast<LPARAM>(small_icon));
Obviously in the first example, the first form requires an extra local variable be allocated from the stack, but I personally think it is easier to read/debug.
Again, in the second example an extra local variable is required, which once more I think is easier to read. However, perhaps there are performance gains to be had from the first form that compensate for a loss in readability?
I find the second one better. The new variable adds no more semantic to the code. It is just a dummy variable. Its name, comparission, says nothing. Perhaps you could have written:
bool is_specific_name = strcmp(name,"Specific Name") == 0;
if (is_specific_name) {
...
}
At least now the variable tells the reader something. Maybe someone unfamiliar with strcmp would appreciate it. Although, if the audience of your code are people familiar with C, then they'd probably know all about strcmp and they would probably appreciate the shorter code.
However, if we are writing C++, why are we using strcmp and not string comparison? Why use C's char array? Certanly
if (name == "Specific Name") {
...
}
would be the most semantic of all expressions. In that case the extra variable seems quite unecessary.
As for performance, an optimizing compiler should generate the same code for both constructions, given that you don't use the variable anywhere else.
Smart compilers might generate same binary code for both styles. So you can do some compilation and disassembling to confirm it, if you are really intrested.

Using unique dynamic variable names (not variable values!)

Ok so, this is more a sanity check than anything else.
Lets asume we have a struct called lua_State, now I need to create a uncertain amount of unique lua_State's. To make sure I don't use the same variable name twice I would need to have some sort of way to get an unique variable every time i make a new state.
However there is only one way (I think?) to create a new state, and that is as follows:
lua_State *S = lewL_newstate();
Now I would need some way to dynamically change that "S" to.. whatever.
For example: If I had 4 lua files, and I wanted to load each into their own lua_State, I would call: lua_State *A = lewL_newstate(); for the first, lua_State *B = lewL_newstate(); for the second, and so on. Keep in mind the number of lua files varies so creating a fixed number of states probably won't go over well.
How would I go about doing this?
clarification:
.h
struct lua_State
.cpp
createNewState(Lua_State* something){
lua_State* something = luaL_newstate();
}
I thought about creating a
std::map<int, lua_State*> luaMap;
but then I would still have the problem of actually generating (for lack of better words) a variable name for every int-index.
So, have I been drinking too much coffee and is there a glaringly obvious simply solution to what I am trying to do, or should I just stop coding untill the crazy blows over?
Thanks in advance.
Use a std::vector to both store the created states and generate sequential identifiers (i.e. array indices). Unless I'm missing something, then you are grossly over-complicating your requirements.
std::vector<lua_State *> stateList;
// create a new Lua state and return it's ID number
int newLuaState()
{
stateList.push_back(luaL_newstate());
return stateList.size() - 1;
}
// retrieve a Lua state by its ID number
lua_State * getLuaState(int id)
{
assert(0 <= id && stateList.size() > id);
return stateList[id];
}
Can't you use std::map<std::string, lua_State*> and use the script name as an index to the state?
Why do you need a variable name for every index? Why is it not good enough to refer to, for example, luaMap[0] and luaMap[1]? I don't think there's really any way to do what you want. You need some sort of dynamic array, like a std::vector.
GiNaC does this, but the name has to be explicitly given to a variable