Valuator fails

Discuss the new AI features ("NoAI") introduced into OpenTTD 0.7, allowing you to implement custom AIs, and the new Game Scripts available in OpenTTD 1.2 and higher.

Moderator: OpenTTD Developers

Post Reply
User avatar
Ralph
Engineer
Engineer
Posts: 87
Joined: 21 Jun 2004 15:25

Valuator fails

Post by Ralph »

Not sure if this is a bug, or just how valuators behave, but you can't do this

Code: Select all

//set up a class with a valuator function
class foo
{

number = null;

constructor(bar)
{
number = bar;
} 

function compare(index)
{
if(index > number) return true;
return false;
}
}//finish class

//now create an instance of foo and use the function

local fooinstance = foo(10);
local towns = AITownList();

towns.Valuate(fooinstance.compare);
The vaulator line will fail with index number does not exist. It seems when you call an instance function as a valuator, the class function (foo.compare) is called rather than the instance one (fooinstance.compare), hence it cannot access instance variables, I guess a workaround is to pass the instance in as a parameter, but its not very neat.

Forgive me if this has come up before/is just the way things work.
TrueBrain
OpenTTD Developer
OpenTTD Developer
Posts: 1370
Joined: 31 May 2004 09:21

Re: NoAI Branch - An AI Framework

Post by TrueBrain »

Ralph wrote:Not sure if this is a bug, or just how valuators behave, but you can't do this

(...)

The vaulator line will fail with index number does not exist. It seems when you call an instance function as a valuator, the class function (foo.compare) is called rather than the instance one (fooinstance.compare), hence it cannot access instance variables, I guess a workaround is to pass the instance in as a parameter, but its not very neat.

Forgive me if this has come up before/is just the way things work.
Too bad this can't work. If you call 'fooinstance.compare', on the stack really is pushed foo.compare, and the instance it belongs to is lost (for ever). Therefor, the Valuator function has no way of knowing which instance 'fooinstance' is. To avoid strange crashes and other Squirrel related stuff, the 'list' instance is sent as 'this' (yes, VERY bad, I know, but there is no other way for now). I looked at the code, looked in the stack, and in many other places, but I see no way to solve this problem now or in the near future ... so for now I suggest not using such functions, and give the 'number' as extra param (like in the examples). The function in the Valuator is STATICly called, and should be handled as such :)
The only thing necessary for the triumph of evil is for good men to do nothing.
Post Reply

Return to “OpenTTD AIs and Game Scripts”

Who is online

Users browsing this forum: No registered users and 21 guests