Lua override class function in included file - class

I'm sorry I'm new to LUA scripts and I have to work on code written by others.
Please don't focus on code, my problem is only about included files and priority evaluating which function has to be called, in case of overriding.
Let's say I have a file Terrain.lua containing a class Terrain, which has a function Terrain:generate() and Terrain:generate() calls Terrain:getLatitude().
Terrain was included in a script MyScript.lua, which overrided Terrain:getLatitude() as follows:
include("Terrain");
function Terrain:getLatitude()
new code;
end
function myFunction()
local myTerrain = Terrain.create();
myTerrain.generate();
end
This has the effect of overriding getLatitude(): when myTerrain.generate() is called, generate() is the code from the included "Terrain", but getLatitude() is the local function with the new code, even if called by a function from the included class.
Now let's say I want to put some of the code in an external file Custom.lua. Custom (and not MyScript) has to override getLatitude().
This is the situation:
Terrain.lua contains Terrain class and these functions
Terrain.create()
Terrain.generate()
Terrain.getLatitude()
MyScript.lua is the script being executed, and include Custom:
include("Custom");
function myFunction()
return customFunction()
end
Custom.lua contains:
include("Terrain");
function Terrain:getLatitude()
new code;
end
function customFunction()
local myTerrain = Terrain.create();
myTerrain.generate();
end
Now, if I call customFunction() from MyScript, getLatitude() from Terrain is used, instead of getLatitude() from Custom. I assume ovveride is possible only inside the currenti file being executed? How can I achieve overriding in an included file?
I hope this example is enough to understand my problem, without posting a lot of code. Thank you.

Firstly, some corrections: there is no local function's in your question; include is not part of any lua standard, what that function actually does may be quite important.
Finally, Lua does not have actual class system, what you use in the question is merely a syntactic sugar (misleading and confusing as I find it) over table assignments. Lua is an interpreted language, so what may seem to you as a class definition is not a static structure known from the very beginning of the program execution but a code that gets executed from the top of the file to the bottom.
Thus, if we assume that include is similar to the require, then the your question code will be equivalent to the following:
do--terrain.lua
Terrain = {
create=function()
local created_object
--some code to assign value to created_object
return created_object
end
}
Terrain.generate = function(self) end
Terrain.getLatitude = function(this_is_a_self_too)
--some code that uses `also_self` as a reference to the object when called as object:generate()
end
--do end block is essentially an equivalent of file, its local variables are not seen outside
--global variables it has assigned (like `terrain`) will stay accessible AFTER its end
--changes it done to global variables will also remain
end
do--Custom.lua
Terrain.getLatitude = function(this)--this is the assignment to a field in a table stored in the global variable Terrain
--this function will replace the one assigned to the `getLatitude` field
end
customFunction = function()
local myTerrain = Terrain.create();
myTerrain.generate();--this one probably needs `:` instead of `.`
--depends on actual code inside terrain.lua
end
end
do--MyScript.lua
myFunction= function()
return customFunction() --this line calls the global variable customFunction
end
end
Thus if your actual setup is similar to the one in question, then the "override" will take effect after the Custom.lua is executed and for all the subsequent calls to the Terrain.getLatitude regardless of whether or not they've called the file. (And any later file can override it again, and all calls after that will be using the new one)
It is probably more complicated to do a limited override in this setup. That again depends on the actual details of how your team has defined the Terrain class and the class system itself.

Related

Making a DFH functions Header file

Edit: This question is not off-topic as it describes an issue in data file handling with Turbo C++.
First of all, Turbo C++ is because of my school. Don't comment telling me to stop using it, I'm forced.
Introduction: I'm trying to build a DFH library, so I made all these functions to write, read, insert, delete, modify, etc.
I used stings to make the functions work for any filename passed to them.
What I understand (self-learned) from the whole making a class and then passing it's object in the read_stream.read((char*)& Object_1, sizeof(Object_1)); form to read the file, that you wrote using the same object is that: the class works as sort of a template to print data onto the file.
Question: I want to use them with different objects of different classes, so the class whose object these DFH functions use for performing the desired task should be sort of like a template.
I was thinking on doing something with templates or abstract class and inheritance but I'm a beginner so I need someone to point me in the right direction!
To clear up: I want to use the same functions by just including this source file into other programs containing different classes.
Example Code
class Data {
int user_id;
public:
void enter() { //Input Function
cout<<"\nID: ";
cin>>user_id;
};
void write(char* file_1) { //File Write Function
clrscr();
Data Object_1;
char ch;
int records_read =0;
ofstream fout;
fout.open(file_1, ios::binary|ios::noreplace);
do {
records_read++;
Object_1.enter(records_read);
fout.write((char*)& Object_1, sizeof(Object_1));
cout<<"\nDo you want to continue? Y/N - ";
cin>>ch;
} while((ch=='y')||(ch=='Y'));
cout<<"\nWrite Successful!";
fout.close();
}
How do I make the function write() work with any other class, without having to explicitly change the statement Data Object_1; ?

UVM- run test() in top block and Macros

I'm reading the following guide:
https://colorlesscube.com/uvm-guide-for-beginners/chapter-3-top-block/
In Code 3.2 line 24- run_test();
I realized that it supposed to execute the test, but how it know which test, and how, and why should I write it in the top block.
In Code 4.1 lines 11-14 (https://colorlesscube.com/uvm-guide-for-beginners/chapter-4-transactions-sequences-and-sequencers/):
`uvm_object_utils_begin(simpleadder_transaction)
`uvm_field_int(ina, UVM_ALL_ON)
`uvm_field_int(inb, UVM_ALL_ON)
`uvm_field_int(out, UVM_ALL_ON)
`uvm_object_utils_end
Why should I add the "uvm_field_int" , what would happend if i didn't add them, and what is "UVM_ALL_ON"?
run_test is a helper global function , it calls the run_test function of the uvm_root class to run the test case. There are two ways by which you can pass the test name to the function.The first is via the function argument and the second is via a command line argument. The command line argument takes precedence over the test name passed via the function argument.
+UVM_TESTNAME=YOUR_TEST_NAME
run_test("YOUR_TEST_NAME");
run_test function in the uvm_root uses the factory mechanism to create the appropriate instance of the umm_test class and so the test case must register itself with the factory using the macro `uvm_component_utils for the factory mechanism (create_component_by_name) to function.
class YOUR_TEST_NAME extends umm_test ;
// register the class with the factory
// so that run_test can find this class when the
// string test_name is passed to it.
`uvm_component_utils(YOUR_TEST_NAME)
.....
endclass
The run_test function then kicks of the uvm_phases (..,build_phase,connect_phase,...) starting the uvm portion of the simulation. There should be no time ticks consumed before the run_phase starts , so it is essential that run_test case is called in the initial block itself. Also we want the uvm and test bench to be ready to drive and receive data as soon as the RTL is ready for which it is essential that we start the run_test at the earliest. Any delay in doing so will generate an error.
`uvm_field_int/uvm_field_object/.. are called field automation macros. They are not mandatory in the class definition and are provided as a helper macros to ease the use of many common/routine functions of the uvm_object. Examples of thse functions in uvm_object are - copy,compare,pack,unpack,print, etc and these macros generate code to automatically use these functions.
If you are not using the uvm_object common functions leaving out these macros from the class definition will not produce any errors.
In case you implement you own version of the common operations you can also leave out these macros from the class.
UVM_ALL_ON - enables all functions like compare/copy/... to be implemented for the particular field.
link with examples -
http://www.testbench.in/UT_04_UVM_TRANSACTION.html
For example the uvm_object has a compare function which compare two instances of the same class and return true if all the variables in the class are equal.
virtual function bit do_compare( uvm_object rhs, uvm_comparer comparer );
.....
// return 1 if all the variables match
return ( super.do_compare( rhs, comparer ) &&
this.var_1 == rhs.var_1 &&
this.var_2 == rhs.var_2 &&
......
this.var_n == rhs.var_n );
endfunction: do_compare
// use in main code
if ( new_class.compare(old_classs) )
...
//instead of
if ( new_class.var1 == old_class.var1 && new_class.var2 == old_class.var2 && ... new_class.varn == old_class.varn )
...
The above compare has to be written for each class and updated and maintained for every new variable that is added to the class. This could become error prone as newer variables are added. A similar process has to be followed for all the standard functions uvm_object provides.
The field automation macro generates function to address all these functionality automatically. So doing a do_print for a class with the macros will print out all the fields without explicitly writing any code for it.
// compare/print/.. functions for class simpleadder_transaction are provided by using `uvm_field_int macro.
`uvm_object_utils_begin(simpleadder_transaction)
`uvm_field_int(ina, UVM_ALL_ON)
`uvm_object_utils_end
BUT a word of caution , the use of these macros are discouraged as they add a significant amount of code into the class.. Most of these functions may not be needed by the class yet they get generated by default.
run_test is defined in the documentation (link) as:
virtual task run_test (
string test_name = ""
)
So, in principle, you can state there the test name as a string. But what's usually done is to pass it in the command line of your simulator using the argument: +UVM_TESTNAME=TEST_NAME
The uvm_object macros are a bit more complicated. They generate several methods and more importantly they register the object in the UVM factory, which is what makes them necessary (at least if you are using, as you should, the factory to create them). Citing from the UVM Class Reference documentation (Section 20.2 Component and Object Macros):
Simple (non-parameterized) objects use the uvm_object_utils* versions,
which do the following:
Implements get_type_name, which returns TYPE as a string
Implements create, which allocates an object of type TYPE by calling its constructor with no arguments. TYPE’s constructor, if
defined, must have default values on all it arguments.
Registers the TYPE with the factory, using the string TYPE as the factory lookup string for the type.
Implements the static get_type() method which returns a factory proxy object for the type.
Implements the virtual get_object_type() method which works just like the static get_type() method, but operates on an already
allocated object.

Constructor that takes a static temp table as input (Progress ABL)

I have a class who's main purpose revolves around a temp table. I want to make a constructor that takes an identical temp table as input.
So far the compiler chokes on any attempt to pass a temp table as a input parameter. If I use a table handle instead, it works. But I'd rather not copy from a dynamic table to a static one.
Progress wants the tables to match up at compile time, but I know they'll be the same - the're defined in a .i file.
Is there an easy way to line up the tables, or am I stuck parsing it out one field at a time?
Works like a charm to me.
CLASS Test.TTOO.TempTableWrapper:
{Test/TTOO/ttCustomer.i}
CONSTRUCTOR PUBLIC TempTableWrapper (TABLE ttCustomer):
FOR EACH ttCustomer:
DISPLAY ttCustomer.CustNum ttCustomer.Name .
END.
END CONSTRUCTOR.
END CLASS.
and the caller:
ROUTINE-LEVEL ON ERROR UNDO, THROW.
USING Test.TTOO.* FROM PROPATH.
DEFINE VARIABLE oWrapper AS TempTableWrapper NO-UNDO .
{Test/TTOO/ttCustomer.i}
/* *************************** Main Block *************************** */
CREATE ttCustomer.
ASSIGN ttCustomer.CustNum = 42
ttCustomer.Name = "It works" .
oWrapper = NEW TempTableWrapper(TABLE ttCustomer ) .
You can also pass the temp-table by-ref:
oWrapper = NEW TempTableWrapper(TABLE ttCustomer BY-REFERENCE) .
However, then the temp-table data is only availalbe during the constructor as BY-REFERENCE calls "overlap" the temp-table within the callee only for the duration of that call.
For permanent "BY-REFERENCE", use the BIND keyword on the call and the paramter - in which case the callee must define the temp-table as REFERENCE-ONLY.
Note, it's not required (although recommended at least by me) to define the temp-tables in include files. At runtime and compile time, the schemas just need to match.
When the compiler does not like your call, delete the classes r-code and recompile.

Extending matlab classes: new methods for built-in classes

I inherited a complete toolbox, last revised in 2006, and I must update it to the latest version of Matlab. This toolbox defines some classes and defines methods for built in classes. More specifically, it creates some extra methods for objects of the control systems toolbox classes lti, ss, zpk and tf.
The first part, rebuilding the new classes, is already done. I am having troubles with the new methods for existing classes.
Since the code was written in an older version of Matlab, it uses class folders like #lti, #ss, #zpk to define the new methods. Now I need to keep the functionality, but using the new OOP model, in which not all #-folders are visible.
Does anybody know how to do that?
Since I had no luck trying to find a solution, I had to find one on my own. This is the method I came up with.
The toolbox had three new method for the zpk class. I created a new class, called sdzpk, and declared it to be a subclass of the built in zpk class. Then, wherever any of the new methods were used, I first converted the object to the new class before passing it to the method.
The following code may ilustrate that better:
Class definition file:
classdef sdzpk < zpk & sdlti
methods (Access = public)
function obj = sdzpk(varargin)
% Constructor method. Long code here to perform data validation
% and pass information to the zpk constructor
obj = obj#zpk(args{:});
end
% Existing methods
% This are the old files I inherited. No need to edit them.
tsys = ctranspose(sys);
sys = delay2z(sys);
sysr = minreal(sys,tol);
F = minreals(F,tol);
FP = setpoles(F,p);
F = symmetr(F,type,tol);
F = z2zeta(F,tol);
end
end
At several locations within the toolbox, the function minreals is called. All those calls were replaced with:
minreals(sdzpk(obj))
In that way, I make sure the new class is used and the correct method is applied.
I hope this helps somebody.

MobileSubstrate: MSHookFunction example

I am trying to write a MobileSubstrate plugin which hooks into a C-method. I tried to edit the famous "ExampleHook", by just writing a demo MSHook and hook it in the Initialize method.
This is probably too optimistic and it doesn't work. But I cannot find anywhere a simple example of a MSHookFunction(). There is barely information about this on the Internet. It might be possible I misunderstood the whole concept of MSHookFunction.
Please, can anybody help me out with a little example code? I would deeply appreciate any help.
Best regards,
Marc Backes
I realize you have found this, but I am posting this answer to help whoever else may be needing this.
A simple example can be found at the MobileSubstrate article on the iPhone Dev Wiki, and an actual example of this in a project is at this bit of User Agent Faker.
But what is an answer without an actual explanation? Therefore, here we go!
void MSHookFunction(void* function, void* replacement, void** p_original); is the function definition for MSHookFunction, the magic function which causes your function X() to be interposed by Y(), for instance.
That is, when a program commonly would call X(), the call will be redirected to Y() instead. This is pretty much a basic explanation of function interposing.
Now, what are the parameters, and their usefulness?
function is a function pointer to the function you want to interpose. That would be a function pointer to X(), in our quick explanation.
replacement is a function pointer to the function you want function to be interposed with. In our quick explanation, that would be a function pointer to Y().
p_original is a pointer to a function pointer, which from now on will point to what function used to be.
The reason this is there is simple: If you intend to modify behavior, but not suppress it, you'll still need to call what X() used to be. But a common call to X() wouldn't work as intended, as it would end calling Y() instead of the default function.
Therefore, you have a function pointer to call X() as if it wasn't interposed.
Now, explaining the devwiki example:
static void (*original_CFShow)(CFTypeRef obj); // a function pointer to store the original CFShow().
void replaced_CFShow(CFTypeRef obj) { // our replacement of CFShow().
printf("Calling original CFShow(%p)...", obj);
original_CFShow(obj); // calls the original CFShow.
printf(" done.\n");
}
...
// hook CFShow to our own implementation.
MSHookFunction(CFShow, replaced_CFShow, &original_CFShow);
// From now on any call to CFShow will pass through replaced_CFShow first.
...
CFShow(CFSTR("test"));
Here, we:
Pass a pointer to CFShow, the function we want to change default behavior from as the function parameter.
Pass a pointer to the function we just created, replaced_CFShow as the replacement parameter. That is, whenever CFShow would be called by default, replaced_CFShow will be called instead.
We pass a pointer to the original_CFShow function pointer as the p_original parameter. Since we still want the things CFShow still does by itself to be done inside our replacement function, we call it.