Jump to content

Calling LUA Script function from C++ with arguments?


Roland
 Share

Recommended Posts

Calling a Lua Script function from C++ without arguments works just fine. No problem. But when it comes to bringing along an argument I need some hint. Here is an example.

 

LUA:

Script.myval = 10

function Script::increment()
self.myval = self.myval + 1
end

function Script::add( val )
self.myval = self.myval + val
end

 

C++: (assuming we have the entity to which the script attached)

 

entity->CallFunction( "increment" ); // works fine. no problem

 

Any idea how to add argument for the call of "add" ? I understand that this has to be done using the Interpreter class. But how ?

AV MX Linux

Link to comment
Share on other sites

Here's an example:

	bool Entity::CallFunction(const std::string& name, Entity* entity, const Vec3& position, const Vec3& normal, const float speed)
{
	if (component==NULL) return false;
	bool success = false;

	//Get the component table
	int stacksize = Interpreter::GetStackSize();

	//Get the global error handler function
	int errorfunctionindex = 0;
#ifdef DEBUG
	Interpreter::GetGlobal("LuaErrorHandler");
	errorfunctionindex = Interpreter::GetStackSize();
#endif
	Push();
	Interpreter::GetField("script");
	if (Interpreter::IsTable())
	{
		Interpreter::GetField(name);
		if (Interpreter::IsFunction())
		{
			Interpreter::PushValue(-2);//Push script table onto stack
			Interpreter::PushObject(entity);
			Interpreter::PushVec3(position);
			Interpreter::PushVec3(normal);
			Interpreter::PushFloat(speed);
#ifdef DEBUG
			errorfunctionindex = -(Interpreter::GetStackSize()-errorfunctionindex+1);
#endif
			success = Interpreter::Invoke(5,0,errorfunctionindex);
		}
	}
	Interpreter::SetStackSize(stacksize);
	return success;
}

My job is to make tools you love, with the features you want, and performance you can't live without.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...