How can we tell if the calling of $cast is of a function or of a task. How would calling of each differ? One thing I understand is that with the function call, I'll be able to use assert(). But other than that, what tells us if the call is of the $cast function or the $cast task? In either case, we'd be doing something like $cast(pkt, pkt1);
LRM gives the syntax of the $cast function as
function int $cast( singular dest_var, singular source_exp );
and of the $cast task as
task $cast( singular dest_var, singular source_exp );
and goes on to explain that
Use of $cast as either a task or a function determines how invalid assignments are handled.
When called as a task, $cast attempts to assign the source expression
to the destination variable. If the assignment is invalid, a run-time
error occurs, and the destination variable is left unchanged.
When called as a function, $cast attempts to assign the source expression
to the destination variable and returns 1 if the cast is legal. If the
cast fails, the function does not make the assignment and returns 0.
When called as a function, no run-time error occurs, and the
destination variable is left unchanged.
Please explain.
Your comment is correct: if $cast is used as part of an expression, it is considered called as a function. That wording is derived from Verilog terminology when functions could only be used in an expression and never could exist as a simple statement like a task call. But once SystemVerilog added functions with void return types, that wording does not fit as well anymore.
Related
I'm new to Lua and trying to understand the concept of OOP in Lua. To do so, I've tried creating an object and creating methods and "private variables". My issue is when I try to use "setters" or "getters", it's indicating that my tables are returning NIL which means I'm either having a scoping issue or something else I can't figure out.
The kicker is I'm using an example from an online Lua coding tutorial, and when I run the tutorial it works flawlessly. However, when I run mine, I get NIL or nothing outputs whenever I try to "get" or return a value from one of the member functions.
I'm using a couple of different environments:
ZeroBrain
Sublime Text
Lua for Windows
Do you know why my code is not returning populated tables?
newPlayer = function(n, h, a, r)
player = {}
n = n or ""
h = h or 100
a = a or 100
r = r or 0
function player:getPlayerName()
return n
end
function player:getPlayerHealth()
return h
end
function player:getPlayerArmor()
return a
end
function player:getPlayerRank()
return r
end
function player:setPlayerName(arg)
n = arg
end
function player:setPlayerHealth(arg)
h = arg
end
function player:setPlayerArmor(arg)
a = arg
end
function player:setPlayerRank(arg)
r = arg
end
function player:connect(arg)
print(string.format(" %s joined" , arg))
end
return player
end
player1 = newPlayer("John", 100, 100, 1000)
player1.getPlayerName()
Your code does not contain "populated tables" to return.
Your newPlayer function does create a table, and it does return it. It creates a number of functions within that table. But that's all newPlayer does: creates a table and puts some functions in it.
The data accessed by those functions is not part of the table. n, h, a, and r (BTW, please use better variable names) are all local variables. Your inner functions will access the specific stack containing those variables, but the variables themselves will not be magically associated with the table.
Your principle problem is almost certainly with the setters. And it comes from a combination of this:
function player:setPlayerName(arg)
with this:
player1.getPlayerName()
When you create a function using a : character between a table name and the function's name, you are using syntactic sugar for a function which implicitly takes as its first argument a value called self. As the name suggests, this is supposed to represent the object which this function is being called upon. So your function creation code is equivalent to:
function player.setPlayerName(self, arg)
Since you create all of your functions with :, all of your functions take at least one parameter.
The : syntax can also be used when calling such functions. If you did player1:getPlayerName(), this would cause the table you accessed to find the getPlayerName function to be used as the first argument in the function call. So that line would be equivalent to player1.getPlayerName(player1).
Obviously, these two syntaxes are mirrors of one another: functions created with : take a parameter that is expected to refer to the table it is being called on, and functions called with : will be given the table which was accessed to get that function.
But... your code didn't stick to the symmetry. You created the functions with :, but you call them with .
Now, you get functions are able to get away with this because... well, none of your values are actually part of the table. So your get functions just return the local value that they adopted from their creating context.
The set functions pose a problem. See, they take a parameter. But because the function was declared with :, they really take two parameters, the first being the implicit self.
Now, : syntax is just syntactic sugar; it's just a convenient way to do what you could have done yourself. So it is in theory OK to call a function with . even if you created it with :. But if you do so, you must pass the table as the first parameter. Though your code doesn't show it, I strongly suspect you didn't do that.
If you called player1.setPlayerName("foo"), what will happen is that the implicit self parameter will get the value "foo", and the arg parameter will be nil. And you will assign that nil value to the n local variable. So subsequent calls to player1.getPlayerName() will return nil.
Basically, what's going on here is that you're combining two different ways of creating objects in Lua. You stored your private data in a way that external code cannot access (ie: local upvalues), but that data is now no longer part of the table itself. Which means that, although you dutifully create those functions with : syntax to indicate that they take a self table, they never actually use that table. And because they never use the table, it's a lot harder to figure out what's going wrong.
Basically, the key here is to be symmetrical. If you create a function with :, then you should either call it with : or make sure to pass it the object table as the first parameter.
Broadly speaking, the standard way to create private members is by convention, not by forbidding it. That is, you agree not to mess with any members of a table other than those with certain names. Python convention is to pretend that names starting with _ don't exist, and Lua programs sometimes use that.
Upvalues are an interesting solution for private variables, but they do come with problems. If you want to invent a member variable, you have to do it in a centralized place rather than wherever you might need one. Even if the variable is optional, you have to create a named local at the top of the function.
TLDR of Nicol's answer, see my answer to another question:
function player:setPlayerArmor(arg)
a = arg
end
The : syntax is syntactic sugar. It creates an implicit 'self' argument when declared, and when used. If you declare it one way and use it another, the arguments won't be what you're expecting. Say your player has 100 health. Look at this result:
player1.setPlayerHealth(55, 66)
print(player1.getPlayerHealth())
-- will display '66', not '55' because `:` declares implicit 'self' argument
This displays 66 because the setPlayerHealth function has an implicit 'self' parameter because it was declared with :. If you instead called it
with the ::
player1:setPlayerHealth(55, 66)
print(player1:getPlayerHealth())
-- will display '55' because `:` passes player1 as self
function player:setHealth1(arg)
-- implicit 'self' argument refers to player1 when called on player1
end
-- is the same as
function player.setHealth2(self, arg)
-- with `.` notation, you need to add the 'self' argument explicitly
end
player1.setHealth1(31) -- self argument will be 31 and arg will be nil
player1.setHealth2(32) -- self argument will be 32 and arg will be nil
player1:setHealth1(33) -- self argument will be player1 and arg will be 33
player1:setHealth2(34) -- self argument will be player1 and arg will be 34
I have a pure C function, to which I would like to pass a block (a closure?). As per Apple, the block should always be the last parameter to a function.
double pureCfunctionWithABlockParameter( int ignore, double ignore2, void (^myVoidBlockWithoutParameters)(void) ) {
myVoidBlockWithoutParameters(); /
return 0.0;
}
Next is the Objective C code to call the C function:
- (void) testBlockFunctionality {
declare and define the block:
void (^myBlock1)(void) ;
myBlock1=^(void){ NSLog(#"myBlock1 just logs this message to the console");};
Attempt to invoke the block directly, without parentheses. This doesn't work. Xcode warns result is unused. Block's message is NOT logged to console.
myBlock1;
Now attempt to invoke the block directly, this time with parentheses. This works as intended. No Xcode warnings, and the block's message IS logged to console.
myBlock1();
Now call the function, passing the block as parameter, WITHOUT parentheses. This works as intended, but the syntax is not consistent with the previous invocation of the block.
double someNumber;
someNumber= pureCfunctionWithABlockParameter(0, 1, myBlock1 );
Now call the function, again passing the block as a parameter, this time WITH parentheses. This doesn't work, it won't even compile, as Xcode gives a: "Passing 'void' to parameter of incompatible type 'void (^)(void)'" message.
someNumber= pureCfunctionWithABlockParameter(0, 1, myBlock1());
At the end of it all, I am actually looking to have a block defined that gets passed an int parameter, like this:
void(^block)(int)
But I cannot progress to that because of what I think is a syntax issue.
I've looked in Apple's Block Programming Topics, and even K&R C, but no luck.
The question has caused some confusion, because blocks (in the question's sense) are not a feature of standard C. Apple added them as an extension to its C and C++ compilers when it added them to Objective C, but they are not a C thing outside the Apple ecosystem. I confess that I've no experience actually using them, but as far as I can tell from the docs, such as these, the syntax was chosen so as to be the same for C, C++, and Objective C. Indeed, some sources claim that details of the syntax were chosen specifically to avoid the possibility of conflict with C++.
From a C perspective, accepting a block as a parameter and calling a block received that way are thoroughly analogous to accepting a function pointer and calling the pointed-to function, respectively. Your example C function appears to be correct.
Similar applies to declaring and and working with blocks, in all three languages -- it is analogous to declaring and working with function pointers. I am confident that this was an intentional design consideration. Thus
void (^myBlock1)(void) ;
indeed declares myBlock1 as a block taking no parameters and returning nothing, but does not define its value. Having elsewhere set a valid value for it, such as is demonstrated in the question, the OP observes
Attempt to invoke the block directly, without parentheses. This
doesn't work. Xcode warns result is unused. Block's message is NOT
logged to console.
myBlock1;
, as indeed should be expected. That's a statement expression evaluating to the value of the block, not to the result of executing the block. It is analogous to
int myInt = 1;
myInt; // specifically, analogous to this
To execute a block, one provides a postfix argument list in parentheses (even if the list is empty), just like when calling a function through a function pointer:
Now attempt to invoke the block directly, this time with parentheses.
This works as intended. No Xcode warnings, and the block's message IS
logged to console.
myBlock1();
The presence or absence of an argument list is what disambiguates whether one is accessing the block's value or calling it.
The confusion is about passing a block to a function (or method):
Now call the function, passing the block as parameter, WITHOUT
parentheses. This works as intended, but the syntax is not consistent
with the previous invocation of the block.
double someNumber;
someNumber= pureCfunctionWithABlockParameter(0, 1, myBlock1 );
Yet, contrary to the assertion in the question, that syntax as completely consistent, both internally consistent with other aspects of block syntax and usage, and consistent with analogous function pointer syntax and usage. That passes the block to the function, identifying the block by its name. The block itself is passed, not the result of executing it, because no argument list for it is provided.
At the end of it all, I am actually looking to have a block defined
that gets passed an int parameter, like this:
void (^block)(int)
But I cannot progress to that because of what I think is a syntax
issue.
A C function accepting and using such a block might look like this
void pass_2(void (^do_something)(int)) {
do_something(2);
}
Given variable block declared as shown above, and assigned a valid block as its value, that function could be called like so:
pass_2(block);
Just as we recognize that function pass_2 is called by the presence of an argument list, we recognize that the value of variable block is passed as an argument -- not called -- by the absence of an argument list.
After some discussion on the question found here Correct execution of Final routine in Fortran
I thought it will be useful to know when a function with a pointer result is appropriate to use with a normal or a pointer assignment. For example, given this simple function
function pointer_result(this)
implicit none
type(test_type),intent(in) pointer :: this
type(test_type), pointer :: pointer_result
allocate(pointer_result)
end function
I would normally do test=>pointer_result(test), where test has been declared with the pointer attribute. While the normal assignment test=pointer_result(test) is legal it means something different.
What does the normal assignment imply compared to the pointer assignment?
When does it make sense to use one or the other assignment?
A normal assignment
test = pointer_result()
means that the value of the current target of test will be overwritten by the value pointed to by the resulting pointer. If test points to some invalid address (is undefined or null) the program will crash or produce undefined results. The anonymous target allocated by the function will have no pointer to it any more and the memory will be leaked.
There is hardly any legitimate use for this, but it is likely to happen when one makes a typo and writes = instead of =>. It is a very easy one to make and several style guides recommend to never use pointer functions.
I have a small question in my mind. I researched it on the Internet but no-one is providing the exact answer. My question is:
In data flow coverage criteria, say there is a method which finally returns variable x. When drawing the graph for that method, is that return statement considered to be a use of x?
Yes, a return statement uses the value that it returns. I couldn't find an authoritative reference that says so in plain English either, but here are two arguments:
A return statement passes control from one part of a program to another, just like a method call does. The value being returned is analogous to a function parameter. return therefore is a use just like being a function parameter is a use.
The other kind of use in data flow analysis is when a value leaves the program and has some effect on the outside world, for example by being printed. If we're analyzing a method, rather than an entire program, return causes the value to leave the scope which we're analyzing. So it's a use for the same reason that printing is a use.
I keep reading (for example in the Closure Compiler and other compilers) that inlining of functions isn't always safe. Could you please provide an example when inlining of functions shouldn't be done?
In many languages, inlining a function will have no observable semantic effects, although it is likely to affect the compiled size and execution time of the program. However, that is not true in languages in which the call stack and/or local variable bindings are visible.
As a simple example, in Javscript the local variable arguments always refers to an array-like object containing the arguments to the current function call. Clearly, if the function in which it occurred were inlined, its semantics would change. An inliner would have to either refuse to inline a function whose body references arguments or it would have to modify the code in a way which preserved the semantics, possibly by creating another local variable with a different name and substituting the reference.
Another example would be the (non-recommended) use of eval. Name lookup in the string passed to eval is done within the scope of the function which calls eval. For example:
inner = function(s) { var x = 4; return eval(s); }
outer = function(s) { var x = 3; return inner(s); }
outer("x+1")
Here the value returned by outer is 5. If inner were inlined, which would require renaming its local variable x to avoid name conflict, the value returned would be 4. (If both inner and outer were inlined, the value would probably be something else again.)
In general, it's going to be very difficult to inline a function which calls eval because there is no easy way to know the contents of the argument to eval.