passing a struct as an argument

I am trying to pass a structure as an argument to a function that saves the data in the struct to a file. For some reason the data existing in the struct gets reset(ints become 0, bools become false).

The struct:
1
2
3
4
5
6
7
8
9
10
11
#ifndef OPTIONS_H
#define OPTIONS_H

typedef struct
{
	bool smoothTextures;
	int volume;
	int maxFps;
} Options;

#endif // !OPTIONS_H 


The function prototype:
 
void SaveFile(const char* fileName, const Options options);


The function: (the functions that begin with lua_ are part of the lua library and shouldn't be relevant)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
void FileManager::SaveFile(const char* fileName, const Options options)
{
	std::cout << options.maxFps << std::endl;
	std::cout << options.volume << std::endl;
	std::cout << options.smoothTextures << std::endl;

	lua_State *L = luaL_newstate();
	luaL_openlibs(L);

	if (luaL_loadfile(L, "Lua/SaveFile.lua") || lua_pcall(L, 0, 0, 0)) //open file
	{
		std::cout << "error writing to file: " << fileName << std::endl;
		lua_close(L);
	}

	lua_getglobal(L, "saveFile"); //get the function
	lua_pushstring(L, fileName); //push the fileName arg

	lua_newtable(L); //create the data to be saved

	lua_pushboolean(L, options.smoothTextures); //enter the data to be saved
	lua_pushnumber(L, options.volume);
	lua_pushnumber(L, options.maxFps);

	std::cout << lua_tostring(L, -1) << std::endl;
	std::cout << lua_tostring(L, -2) << std::endl;
	std::cout << lua_tostring(L, -3) << std::endl;

	lua_settable(L, -1); //add the data to the table
	lua_settable(L, -2);
	lua_settable(L, -3);

	lua_settop(L, -4); //set the created table to the top of the stack

	if (lua_pcall(L, 2, 0, 0) != EXIT_SUCCESS)
		std::cout << "error running function: saveFile" << std::endl;

	lua_close(L);
}


The function call:
 
File.SaveFile("options.txt", options);


I have looked at multiple other forum posts and I know that with large structs you should pass them as references or pointers but this struct is very small so it shouldn't cause and performance problems. The output when I run the function is 0 for all members of the struct.
closed account (o3hC5Di1)
Hi there,

Could you show us the code where you are calling this function?
Also, the normal C++ way of declaring a struct is as follows:

1
2
3
4
5
6
7
8
9
10
11
#ifndef OPTIONS_H
#define OPTIONS_H

struct Options
{
	bool smoothTextures;
	int volume;
	int maxFps;
};

#endif // !OPTIONS_H  


All the best,
NwN
Apologies as this is a bit off topic, but where exactly in that method are you saving the file?


Just read your last paragraph. Have you tried passing it in by reference just to see if there's a difference? (not that it should actually. i think nWn is on the right path. how is this called?).
Last edited on
Topic archived. No new replies allowed.