When I Use EG(active_symbol_table) I get error - pecl

I write a pecl function named sample_isset, and its code is :
PHP_FUNCTION(sample_isset) {
zval **fooval;
if(EG(active_symbol_table) == NULL) {
php_printf("the active symbol table is NULL");
}else if(zend_hash_find(EG(active_symbol_table),"foo",4,
(void **) &fooval) == SUCCESS){
php_printf("Got the value of $foo!");
} else {
php_printf("$foo is not defined!");
}
}
And I want to use this function to see if current symbol table has a $foo variable.
When I use it in global scope, it works well.
But When I use it in another function for example hello, I go a error, and see nothing .
The hello function may be like this.
function hello(){
sample_isset();
}
I don't know why I got an error.

It seems that the php function used the lazy loading, the active_symbol_table doesn't always exist, so You should use zend_rebuild_symbol_table before EG(active_symbol_table) .

Related

How to use if statement when function returns 2 arguments?

I recently created a function that checks if a pair exists in my swap smart contract.
The functoin looks like this:
function checkIfPairExists(address _token1, address _token2) internal returns(uint, bool) {
for (uint index = 0; index < tokenPairs.length; index++) {
if (tokenPairs[index].token1 == _token1 && tokenPairs[index].token2 == _token2) {
return (index, true);
}
else if (tokenPairs[index].token2 == _token1 && tokenPairs[index].token1 == _token2) {
return (index, true);
} else {
return (0, false);
}
}
}
This function works fine but then when I try to use the function in an if statement like this:
if (checkIfPairExists(_token1, _token2) == (uint256, true))
How do I write it so it is correct? I am trying to receive index of the pair for my array and bool to see if the pair exists. I then need to save that index to find which pair it should add to.
Hope it makes sense.
Let me know if I should rephrase the question so more people will understand it and it can help them.
Thanks
You need to assign the returned values to two separate variables. Then you can validate either of them.
(uint256 index, bool exists) = checkIfPairExists(_token1, _token2);
if (exists == true) {
// do something with `index`
}
As said in the above answer by #pert-hejda, you will need to assign the function return values then you can use those to check the condition. Why? Because multiple returns are represented as tuples and currently the feature you want is not supported in solidity. So, you will need to assign the return values and use those values in conditionals. Thank you.

how to create and export dynamic operators

I have some classes (and will need quite a few more) that look like this:
use Unit;
class Unit::Units::Ampere is Unit
{
method TWEAK { with self {
.si = True;
# m· kg· s· A ·K· mol· cd
.si-signature = [ 0, 0, 0, 1, 0, 0, 0 ];
.singular-name = "ampere";
.plural-name = "ampere";
.symbol = "A";
}}
sub postfix:<A> ($value) returns Unit::Units::Ampere is looser(&prefix:<->) is export(:short) {
return Unit::Units::Ampere.new( :$value );
};
sub postfix:<ampere> ($value) returns Unit::Units::Ampere is looser(&prefix:<->) is export(:long) {
$value\A;
};
}
I would like to be able to construct and export the custom operators dynamically at runtime. I know how to work with EXPORT, but how do I create a postfix operator on the fly?
I ended up basically doing this:
sub EXPORT
{
return %(
"postfix:<A>" => sub is looser(&prefix:<->) {
#do something
}
);
}
which is disturbingly simple.
For the first question, you can create dynamic subs by returning a sub from another. To accept only an Ampere parameter (where "Ampere" is chosen programmatically), use a type capture in the function signature:
sub make-combiner(Any:U ::Type $, &combine-logic) {
return sub (Type $a, Type $b) {
return combine-logic($a, $b);
}
}
my &int-adder = make-combiner Int, {$^a + $^b};
say int-adder(1, 2);
my &list-adder = make-combiner List, {(|$^a, |$^b)};
say list-adder(<a b>, <c d>);
say list-adder(1, <c d>); # Constraint type check fails
Note that when I defined the inner sub, I had to put a space after the sub keyword, lest the compiler think I'm calling a function named "sub". (See the end of my answer for another way to do this.)
Now, on to the hard part: how to export one of these generated functions? The documentation for what is export really does is here: https://docs.perl6.org/language/modules.html#is_export
Half way down the page, they have an example of adding a function to the symbol table without being able to write is export at compile time. To get the above working, it needs to be in a separate file. To see an example of a programmatically determined name and programmatically determined logic, create the following MyModule.pm6:
unit module MyModule;
sub make-combiner(Any:U ::Type $, &combine-logic) {
anon sub combiner(Type $a, Type $b) {
return combine-logic($a, $b);
}
}
my Str $name = 'int';
my $type = Int;
my package EXPORT::DEFAULT {
OUR::{"&{$name}-eater"} := make-combiner $type, {$^a + $^b};
}
Invoke Perl 6:
perl6 -I. -MMyModule -e "say int-eater(4, 3);"
As hoped, the output is 7. Note that in this version, I used anon sub, which lets you name the "anonymous" generated function. I understand this is mainly useful for generating better stack traces.
All that said, I'm having trouble dynamically setting a postfix operator's precedence. I think you need to modify the Precedence role of the operator, or create it yourself instead of letting the compiler create it for you. This isn't documented.

Passing a pipefd through execlp in C

I have looked all over and I cannot seem to figure out how to do this.
I have a parent process that has created a pipe()
Now, I want to fork() the parent and then execlp() and pass the pipe() to the new program as a command line argument.
Then from inside the new program I need to be able to read the pipefd.
I've seen a bunch of stuff on how to do it from inside the same process, but nothing on how to do it like this.
Edit: Initial post is/was rather vague.
What I have so far is:
int pfd[2];
if(pipe(pfd) == -1) {
perror("Creating pipe\n");
exit(1);
}
pid_t pid = fork();
if(pid == -1) {
fprintf (stderr, "Initiator Error Message : fork failed\n");
return -1;
}
else if(pid == 0) { // child process
close(pipe0[1]); // close(write);
execlp("program", "program", pipe0[0], NULL);
}
but then I don't really understand what I should do from inside "program" to get the FD. I tried assigning it to all sorts of things, but they all seem to error.
Thank you in advance!
The forked and execed child automatically inherit the open pipe descriptors and the pipe output is usually fed as standard input so that a command line argument to find the pipe is pretty redundant:
if(!pipe(&pipefd))
switch(fork()) {
case 0: !dup2(pipefd[0],0)&&
execlp("cat","cat","-n","/dev/fd/0",0);
case -1: return perror("fork");
default: write(pipefd[1],"OK\n",3);
}

Expected Identifier error in if statement

I am trying to create a class similar to the built in NSDictionary class, but I want to add some extra functionality and make it easier to use. In the .m file I have the following piece of code:
-(void)newEntryWithKey:(NSString *)theKey andValue:(NSString *)theValue{
if (![theKey isEqual:#""]) && (![theValue isEqual:#""]){
[self.keys addObject:theKey];
[self.values addObject:theValue];
self.upperBound++;
}else{
return
}
}
It gives me an "Expected Identifier" error at the start of the second portion of the if statement after the "&&". Would someone be able to help me with this?
EDIT: The original problem is fixed but now there is a new error at the end of the if statement.
-(void)newEntryWithKey:(NSString *)theKey andValue:(NSString *)theValue{
if (theKey.length && theValue.length) {
[self.keys addObject:theKey];
[self.values addObject:theValue];
self.upperBound++;
}else{
return
} //<-- error here "Expected expression"
}
It should be:
if (![theKey isEqual:#""] && ![theValue isEqual:#""]) {
Though a better check for non-empty strings would be:
if (theKey.length && theValue.length) {
Your original if statement will give incorrect results if either theKey or theValue is nil. My 2nd option works in either case.
Update:
The problem with the updated code is the missing ; after the return statement.
Usually after if you should have one condition in parentheses. You're missing parentheses.

Convert Namespace to a single proc

I have a set of procs and a namespace as you can see below:
namespace eval ::_API {
if {[info exists ::_API::API_ids]} {
catch {API erase -ids [array names ::_API::API_ids]}
}
catch {unset API_ids}
array set API_ids ""
}
proc ::_API::erase { } {
foreach id [array names ::_API::API_ids] {
if {::_API::API_ids($id) == 0} {
continue
}
if {[catch {API -id $id -redraw 0}] != 0} {
set ::_API::API_ids($id) 0
}
}
Redraw ;# I'm not concerned about this part
# and I'm fairly certain it can be ignored
}
proc erase { } {
::_API ::erase
}
::_API::API_ids is an array that contains points (e.g. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15). What the script does is erase points in a table.
I want to convert the namespace ::_API into a proc so that I can use a GUI button to call the proc. It is currently directly after some other scripts (which map the points in the table) and I want to erase them only when required; i.e. when the button will be pressed.
I already tried running ::_API::erase directly but it is not working:
proc ::_API::erase { } {
foreach id [array names ::_API::API_ids] {
if {::_API::API_ids($id) == 0} {
continue
}
if {[catch {API -id $id -redraw 0}] != 0} {
set ::_API::API_ids($id) 0
}
}
Redraw
}
I think that there might be something I'm missing about the namespace. I tried reading the documentation but I don't quite understand really how they work.
The first thing that you really must do is use variable to declare the variable. For some fairly ugly reasons, failing to do that can cause “fun” with variable resolution to make things happen in ways you don't expect:
namespace eval ::_API {
variable API_ids; ##### <<<<<<< THIS <<<<<<< #####
if {[info exists ::_API::API_ids]} {
catch {API erase -ids [array names ::_API::API_ids]}
}
catch {unset API_ids}
array set API_ids ""
}
Secondly, you probably ought to actually think in terms of using real OO for this rather than trying to fake it. For example, with TclOO you'd be writing something like:
oo::class create APIClass {
variable ids
constructor {} {
array set ids {}
}
method erase {} {
foreach id [array names ids] {
if {$ids($id) == 0} continue
if {[catch {
API -id $id -redraw 0
}]} {
set ids($id) 0
}
}
Redraw
}
# Allow something to reference the ids variable from the outside world
method reference {} {
return [my varname ids]
}
}
APIClass create _API
# [_API erase] will call the erase method on the _API object
This simplifies things quite a bit, and in fact you can think in terms of coupling the drawing and the data management quite a lot closer than I've done above; it's just indicative of what you can do. (I find that it makes stuff a lot simpler when I use objects, as they've got a much stronger sense of lifecycle about them than ordinary namespaces.)
What you mean is you want to convert the namespace initialization code into a procedure. The following example should achieve that.
namespace eval ::_API {
}
proc ::_API::initialize {} {
variable API_ids
if {[info exists API_ids]} {
catch {API erase -ids [array names API_ids]}
unset API_ids
}
array set API_ids ""
}
... more definitions ...
::_API::initialize
We start by declaring the namespace. Then replicate the original code in a procedure. As there is no point unsetting a non-existent variable, we move unset into the block that only runs if the variable exists.
At the end of the namespace definitions, initialize the namespace by calling its initialization function.