lua function not returning data - mobile

I am having trouble with a Lua function. I can set the return value for sendAction to a string ("test") and it will return properly. However I can't get the variable of "data" to return as it always returns nil. What am i doing wrong?
local json = require("json");
local action = {};
local action_mt = { __index = action }
---------PRIVATE FUNCTIONS------------
function action:sendAction(values, networkListener)
local data,pos,msg = "";
local params = {}; params.body = "";
for key,value in pairs(values) do
params.body = params.body .. "&" .. key .."=" .. value
end
local function networkListener( event )
if ( event.isError ) then
print( "Network error!" );
else
data,pos,msg = json.decode( event.response );
if (data.errors.count > 0) then
print("errors");
end
end
return data;
end
network.request( "http://127.0.0.1/action.php", "POST", networkListener, params )
end
------PUBLIC FUNCTIONS------
function action:new(action)
local newAction = { action = action };
return setmetatable( newAction, action_mt )
end
function action:createSession()
local data = action:sendAction( { action = "createSession" } );
print(data);
end
return action;

sendAction contains no return statement (in its scope). Why would you expect it to return anything?
The call to network.request is asynchronous, meaning the request actually happens in a separate thread of execution that runs parallel to your main code execution, so the request to the server and response from the server will happen after sendAction has returned.
You want to use the same model network.request does. That is, you pass a callback to sendAction which receives results when they become available. That's a very typical pattern for asynchronous code.
function action:sendAction(values, onSendActionComplete)
local params = {}; params.body = "";
for key,value in pairs(values) do
params.body = params.body .. "&" .. key .."=" .. value
end
local function networkListener( event )
if event.isError then
onSendActionComplete(false, "Network error.");
else
local data,pos,msg = json.decode( event.response );
if data.errors.count > 0 then
onSendActionComplete(false, "JSON decode error.");
else
onSendActionComplete(true, data);
end
end
end
network.request( "http://127.0.0.1/action.php", "POST", networkListener, params )
end
------PUBLIC FUNCTIONS------
function action:new(action)
local newAction = { action = action };
return setmetatable( newAction, action_mt )
end
function action:createSession()
local function onSendActionComplete(success, data)
if success then
print(data);
else
print('Error:', data)
end
end
action:sendAction( { action = "createSession" }, onSendActionComplete)
end

Related

Good ways to navigate and retrieve a value in a table by string path in Lua

Was wondering for a good way to retrieve a value from a table by using a path, like some sort of scope.
As example for a path, "SomePermissions/scope1/B", which gets the permissions from a table that looks like this
{
["SomePermissions"] = {
["scope1"] = {
["A"] = "special",
["B"] = true,
["C"] = false,
}
}
}
What is a good way to do it?
Here is the solution that I made for this: https://stackoverflow.com/a/73013693/11161500
There could be small improvements for it, like giving the function the possibility to specify what to split for. Or when "SomePermissions/scope1/" has that "/" since it splits it, there would be an empty string value.
This is something I came up with, except string_split and string_totable:
function string_totable( str )
local tbl = {}
for i = 1, string.len( str ) do
tbl[i] = string.sub( str, i, i )
end
return tbl
end
function string_split(str, separator, withpattern)
if ( separator == "" ) then return string_totable( str ) end
if ( withpattern == nil ) then withpattern = false end
local ret = {}
local current_pos = 1
for i = 1, string.len( str ) do
local start_pos, end_pos = string.find( str, separator, current_pos, not withpattern )
if ( not start_pos ) then break end
ret[ i ] = string.sub( str, current_pos, start_pos - 1 )
current_pos = end_pos + 1
end
ret[ #ret + 1 ] = string.sub( str, current_pos )
return ret
end
function GetTableValueByScope(tbl, path)
local pathParts = string_split(path, "/")
local enteredPaths = ""
local curLocation = tbl
for i=1,#pathParts do
if (curLocation[pathParts[i]] == nil) then
print("Entry \""..pathParts[i].."\" in \""..enteredPaths.."\", does not exist.")
return nil
end
if (i == #pathParts) then -- If last value in pathParts
return curLocation[pathParts[i]]
else
curLocation = curLocation[pathParts[i]]
enteredPaths = enteredPaths..pathParts[i].."/"
end
end
return curLocation
end
local exampleTable = {
["SomePermissions"] = {
["scope1"] = {
["A"] = "special",
["B"] = true,
["C"] = false,
}
}
}
print(GetTableValueByScope(exampleTable, "SomePermissions/scope1/B"))
-- Prints the value from "B".
print(GetTableValueByScope(exampleTable, "SomePermissions/scope1/ABC"))
-- Prints 'Entry "ABC" in "SomePermissions/scope1/", does not exist.'
local result = GetTableValueByScope(exampleTable, "SomePermissions/scope1")
-- "result" would now be "scope1" table.
-- The function returns a table, like that I can specifiy one scope and return the results within of what it found, and then call the function again with the next scope.
result = GetTableValueByScope(result, "B")
print(result)
-- Prints the value from "B".

PHP - Days of the Week by Array

Here is my code:
$day = 1;
$dayList = array("0"=>"Sunday","1"=>"Monday");
if(in_array($day,$dayList)) {
echo $dayList[$day];
}
I tried $day = 0, and it works good, but it doesn't work if string is 1.
How can I solve this problem?
in_array() checks values, not keys. So in this instance it won't do what you want. isset() is the function you need to use, try this:
if (isset($dayList[$day])) {
...
}
Use array_key_exists :
$day = 1;
$dayList = array("0"=>"Sunday","1"=>"Monday");
if(array_key_exists($day,$dayList)) {
echo $dayList[$day];
}
More info:
http://php.net/manual/en/function.array-key-exists.php
Another method:
You could create a function that returns this value or the key like so:
function getDayOfTheWeek($name)
{
$dayList = array("0"=>"Sunday","1"=>"Monday","2"=>"Tuesday","3" => "Wednesday");
// if a string make sure it's capitalized
if (preg_match('/[^A-Za-z]/', $name)) {
$name = ucwords(strtolower($name));
} else {
// if not a string flip the array and get name
$dayList = array_flip($dayList);
}
return $dayList[$name];
}
// print results for each call to function
var_dump(getDayOfTheWeek('0')); // returns Sunday
var_dump(getDayOfTheWeek('1')); // returns Monday
var_dump(getDayOfTheWeek('Monday')); //returns 1
var_dump(getDayOfTheWeek('Tuesday')); // returns 2

Set a variable in a controller, make some operation and return a new value cakePHP 3

I am using cakePHP 3 and I am trying to set a variable in a controller, use that variable in a function and then pass the new value depends on the queryString the function received.
All this is through ajax's calls.
This is the code and the function I wrote in the controller:
public $taskEditor;
public function checkState(){
if($this->request->query('isFirstTime')){
$value = $this->taskEditor = false;
}else{
$value = !$this->taskEditor;
}
die(json_encode($value));
}
This and others intent Did not work. The variable $taskEditor must store a boolean value. I also try setting a global variable and the set the value in the function beforeRender(Event event), but Did not work.
The response is always false and/or cake don't recognize the $taskEditor variable.
Any help?
Each time you access checkState() the controller is initialized, so $taskEditor is reseted.
You could write this value on session:
public function checkState(){
$session = $this->request->session();
if ( $this->request->query('isFirstTime') == 'true' ) {
$taskEditor = false;
$session->write('taskEditor', $taskEditor);
} else {
$taskEditor = $session->read('taskEditor');
if ( is_null($taskEditor) ) {
$taskEditor = true;
}
$session->write('taskEditor', !$taskEditor);
}
die(json_encode($taskEditor));
}
See Reading & Writing Session Data.

Count result array to string conversion error in codeigniter

I am using this method in my model to get a count result from my database:
function members($group_id)
{
$this->db->where('group_id',$group_id);
$query = $this->db->query('SELECT COUNT(group_id) FROM member');
return $query;
}
And in my controller there is this method:
function total_members ()
{
$group_id = $this->input->post('group_id');
$this->load->model('Member_model');
$members = $this->Member_model->members($group_id);
echo $members;
}
And am getting this weird error which says:
Severity: 4096
Message: Object of class CI_DB_mysqli_result could not be converted to string
Filename: controllers/Payment.php
You need to return a result set which requires another call. In this case I suggest row(). Try these revised functions.
function members($group_id)
{
$this->db->where('group_id', $group_id);
$query = $this->db->query('SELECT COUNT(group_id) as count FROM member');
return $query->row();
}
function total_members()
{
$group_id = $this->input->post('group_id');
$this->load->model('Member_model');
$members = $this->Member_model->members($group_id);
if(isset($members))
{
echo $members->count;
}
}
Learn about the different kinds of result sets here
Try this
Model
function members($group_id) {
return $this->db->get_where('member', array('group_id' => $group_id))->num_rows();
}
Controller
function total_members() {
$group_id = $this->input->post('group_id');
$this->load->model('member_model');
$members = $this->member_model->members($group_id);
print_r($members);
}
In codeigniter there is num_rows() to count the rows. For more information check the documentation .

AngularJs, how to set empty string in URL

In the controller I have below function:
#RequestMapping(value = "administrator/listAuthor/{authorName}/{pageNo}", method = { RequestMethod.GET,
RequestMethod.POST }, produces = "application/json")
public List<Author> listAuthors(#PathVariable(value = "authorName") String authorName,
#PathVariable(value = "pageNo") Integer pageNo) {
try {
if (authorName == null) {
authorName = "";
}
if (pageNo == null) {
pageNo = 1;
}
return adminService.listAuthor(authorName, pageNo);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This function fetches and returns data from mysql database based on "authorName" and "pageNo". For example, when "authorName = a" and "pageNo = 1" I have:
Data I get when "authorName = a" and "pageNo = 1"
Now I want to set "authorName" as ""(empty string), so that I can fetch all the data from mysql database (because the SQL statement "%+""+%" in backend will return all the data).
What can I do if I want to set authorName = empty string?
http://localhost:8080/spring/administrator/listAuthor/{empty string}/1
Thanks in advance!
I don't think that you can encode empty sting to url, what I suggest you to do is to declare some constant that will be your code to empty string - such as null.
Example:
administrator/listAuthor/null/90
Afterwards , on server side, check if authorName is null and set local parameter with empty stirng accordingly.

Resources