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
Related
Assume I have Variable called "Volume", for example. I now have a file with Settings in it. Every Settings looks like this: ":
I now go through this file from top to bottom, and I want the program to store the Setting in a Variable with an equal Name.
e.G. if there is "Volume: 76", I want the program to write "76" into the Variable "Volume". How can I make the program to get the right Variable just by the string? Is this even possible?
There is no code yet, since I haven't started working on it yet. I was making thoughts about it.
You can't use variables directly, since the name must be existent at compile time, but reading a file is runtime.
You can use std::map though. Each settings will be a key, and the value will be read in.
std::map<std::string, std::string> settings;
settings["volume"] = "76";
But, the values ("76" in this case) will be strings as well. You can not use differing types directly.
I think, its possible with type erasure, but thats really advanced (and iam not fluent with it!).
this is more like an ethical question:
if i have the following code:
void changeInt(int& value)
{
value = 7;
}
and i do:
int number = 3;
changeInt(number);
number will have value 7
I know that when the new stack frame will be created for changeInt function, new variables will be created and &value will point to number.
My concern here is that the caller, if it's not paying attention , can be fooled by thinking that is passing by value which actually, on the function frame , a reference will be created.
I know he can look in the header files and it's a perfect legitimate expression but still I find it unethical a bit :)
i think this should be somehow marked and enforced by syntax. Like in C# where you have ref keyword.
What do you guys think ?
This is one of those things where references are less clear than pointers. However, using pointers may lead to something like this:
changeInt(NULL);
when they actually should have done:
changeInt(&number);
which is just as bad. If the function is as clearly named as this, it's hardly a mystery that it actually changes the value passed in.
Another solution is of course to do:
int calculateNewInt(/* may need some input */)
{
return 7;
}
now
int number = 3;
...
number = calculateNewInt();
is quite obviously (potentially) changing number.
But if the name of the function "sounds like it changes the input value", then it's definitely fair to change the value. If in doubt, read the documentatin. If you write code that has local variables that you don't want to alter, make them const.
const int number = 3;
changeInt(number); /* Makes an error */
(Of course, that means the number is not changeable elsewhere either).
I know he can look in the header files and it's a perfect legitimate expression but still I find it unethical a bit :)
I think that's perfectly normal and part of the language. Actually, this is one of the bad things of C and C++: you have to check the headers all the time when dealing with an unknown API, since when calling a function you don't pass by reference explicitly.
That's not the case for all system languages though. IIRC Rust makes it obligatory to pass references explicitly.
That probably wasn't very clear. Say I have a char *a = "reg". Now, I want to write a function that, on reading the value of a, instantiates an object of a particular class and names it reg.
So for example, say I have a class Register, and a separate function create(char *). I want something like this:
void create(char *s) //s == "reg"
{
//what goes here?
Register reg; // <- this should be the result
}
It should be reusable:
void create(char *s) //s == "second"
{
//what goes here?
Register second; // <- this should be the result
}
I hope I've made myself clear. Essentially, I want to treat the value in a variable as a separate variable name. Is this even possible in C/C++? If not, anything similar? My current solution is to hash the string, and the hash table would store the relevant Register object at that location, but I figured that was pretty unnecessary.
Thanks!
Variable names are compile-time artifacts. They don't exist at runtime. It doesn't make sense in C++ to create a dynamically-named variable. How would you refer to it?
Let's say you had this hypothetical create function, and wrote code like:
create("reg");
reg.value = 5;
This wouldn't compile, because the compiler doesn't know what reg refers to in the second line.
C++ doesn't have any way to look up variables at runtime, so creating them at runtime is a nonstarter. A hash table is the right solution for this. Store objects in the hash table and look them up by name.
This isn't possible. C++ does not offer any facilities to process code at runtime. Given the nature of a typical C++ implementation (which compiles to machine code ahead of time, losing all information about source code), this isn't even remotely feasible.
Like I said in my comment:
What's the point? A variable name is something the compiler, but -most importantly- you, the programmer, should care about. Once the application is compiled, the variable name could be whatever... it could be mangled and senseless, it doesn't matter anymore.
You read/write code, including var-names. Once compiled, it's down to the hardware to deal with it.
Neither C nor C++ have eval functions
Simply because: you only compile what you need, eval implies input later-on that may make no sense, or require other dependencies.
C/C++ are compiled ahead of time, eval implies evaluation at runtime. The C process would then imply: pre-process, compile and link the string, in such a way that it still is part of the current process...
Even if it were possible, eval is always said to be evil, that goes double for languages like the C family that are meant to run reliably, and are often used for time-critical operations. The right tool for the job and all that...
A HashTable with objects that have hash, key, Register, collision members is the sensible thing to do. It's not that much overhead anyway...
Still feel like you need this?
Look into the vast number of scripting languages that are out there. Perl, Python... They're all better suited to do this type of stuff
If you need some variable creation and lookup you can either:
Use one of the scripting languages, as suggested by others
Make the lookup explicitly, yourself. The simplest approach is by using a map, which would map a string to your register object. And then you can have:
std::map<const char*, Register*> table;
Register* create(const char* name) {
Register* r = new Register();
table[name] = r;
return r;
}
Register* lookup(const char* name) {
return table[name];
}
void destroy(const char* name) {
delete table[name];
table.erase(name);
}
Obviously, each time you want to access a variable created this way, you have to go through the call to lookup.
I'm not entirely sure what this is called, but I think it is very easy to do.
I have seen some people rename the types of variables to make their code easier to read.
Let's say I have a shop of items and they need a int "itemId".
How could I define so that I can say:
Item getItem(ID itemId);
Insteath of:
Item getItem(int itemId);
I don't nessesarily know if it's any useful to always change code like that. But I would at the very least want the knowledge to know how to do it. Anyways, I'm quite sure it's almost as easy as:
#define ID as int;
or something in that manner. But I just were not able to look it up as I don't remember what the action is called x)
Thanks
C++11:
using ID = int;
C++11 and previous standards:
typedef int ID;
both #define ID int and typedef int ID can work and will have the same effect in your example; But there are differences between the two: the first defines a string literal which will be replaced with "int" at compile time, while the second defines a new data type.
The later is the recommended way, as it is less error prone.
Is it possible to convert strings into variables(and vise versa) by doing something like:
makeVariable("int", "count");
or
string fruit;
cin >> fruit; // user inputs "apple"
makeVariable(fruit, "a green round object");
and then be able to just access it by doing something like:
cout << apple; //a green round object
Thanks in advance!
No, this is not possible. This sort of functionality is common in scripting languages like Ruby and Python, but C++ works very differently from those. In C++ we try to do as much of the program's work as we can at compile time. Sometimes we can do things at runtime, and even then good C++ programmers will find a way to do the work as early as compile time.
If you know you're going to create a variable then create it right away:
int count;
What you might not know ahead of time is the variable's value, so you can defer that for runtime:
std::cin >> count;
If you know you're going to need a collection of variables but not precisely how many of them then create a map or a vector:
std::vector<int> counts;
Remember that the name of a variable is nothing but a name — a way for you to refer to the variable later. In C++ it is not possible nor useful to postpone assigning the name of the variable at runtime. All that would do is make your code more complicated and your program slower.
You can use a map.
map<string, int> numbers;
numbers["count"] = 6;
cout << numbers["count"];
Beginning programmers ask this question regarding every language. There are a group of computer languages for which the answer to this question is "yes". These are dynamic, interactive languages, like BASIC, Lisp, Ruby, Python. But think about it: Variable names only exist in code, for the convenience of the programmer. It only makes sense to define a new variable while the program runs if there's a person to then subsequently type the name of the variable in new code. This is true for interactive language environment, and not true for compiled languages like C++ or Java. In C++, by the time the program runs, and the imaginary new variable would be created, there's no one around to type code that would use that new variable.
What you really want instead is the ability to associate a name with an object at runtime, so that code -- not people -- can use that name to find the object. As other people have already pointed out, the map feature of C++'s standard library gives you that ability.
You might want to look at C++ map.
No. C++ is statically typed, and this goes against that whole paradigm.
I have seen this type of functionality implemented before by storing variables in an stl map.
At least for the (vice versa) there is a possibility with the preprocessor statement stringify #. See this answer on how to convert a C++ variable name into an string.
well i guess u cannot make dynamics variables but u can use some function to write a new variable and its value in any external text file and access its value from that file where ever it is needed (u can also remove the dynamic variable by removing it from the text file.)
theory: variables are places in memory where we store data, identified by a name, we can store data in a text file if processor doesnot allow us to store it in registers, and we can access its value by searching its identity (name of variable) int the text file, our data will be next to it.
its just an idea, it should work but i guess it will be not very simple and ur program will have to pay in terms of speed.