Lua For/do loop - loops

I am trying to create a mod for a game server that i am playing, the idea is to give flag permissions to people based on being a mod or admin. The flags can be assigned by the server owner in a config file.
What i am trying to create, is a for loop that reads a section of the config file and passes the index and value to a function that then sends the information to the server.
function PLUGIN:cmdgiveflags ( netuser , cmd, args )
if (netuser:CanAdmin()) then
local a, targetuser = rust.FindNetUsersByName( args[1] )
if (not a) then
if (targetuser == 0) then
rust.Notice( netuser , "No Players by that name!" )
else
rust.Notice( netuser , "Multiple Players by the name!" )
end
return
end
if ( args[2] == "admin" ) then
**for key,value in pairs(self.Config.admin) do self.addflag(targetuser,key,value) end**
elseif ( args[2] == "mod") then
**for key,value in pairs(self.Config.mod) do self.addflag(targetuser,key,value) end**
else
rust.Notice( netuser , "Invalid Option, must be mod or admin" )
end
else
rust.Notice( netuser , "Only and Admin can use this command" )
end
end
function PLUGIN:addflag (targetuser, key, value)
print ("targetuser is "..targetuser)
**print ("key is "..key)**
**print ("value is "..value)**
if (value == true) then
if (key == "cangod" ) or (key == "canban") or (key == "cankick") or (key == "all") then
rust.RunServerCommand( "oxmin.giveflag " .. targetuser .. " " .. key )
print (targetuser .. " has been given the flag: " .. key )
else
rust.RunServerCommand( "flags.addflag " .. targetuser .. " " .. key )
print (targetuser .. " has been given the flag: " .. key )
end
end
end
The problem that i am having is when the variables key and value are sent to the addflags functions, key shows up as true and value is nil. but if i just do print(key,value) in the for loop they come out as expected. I only just started coding in Lua so I'm not too sure what the rules all are just yet. Any help would be appreciated.
Oh and sorry if the code isnt formatted correctly on the site, not sure how to get it to paste with the correct formatting.

You want self:addflag instead of self.addflag.
The definition
function PLUGIN:addflag (targetuser, key, value)
is sugar for
function PLUGIN.addflag (self, targetuser, key, value)
The call
self:addflag(targetuser,key,value)
is sugar for
self.addflag(self,targetuser,key,value)
So you have to make a call that is consistent with the definition of the function.

Related

how do I insert values while using Hash.Lib while using while loop?

I have the following code... How would I be able to insert values in the array list with different indexes while its looping inside of a while loop? from the 2nd function(HashMine(CarID1))
local function HistoryHash() -- This function is to print out the Hashes "Mined" using Hash.Lib
for Hashindex = 1, #HashHistory do
print("Hash "..Hashindex..":", HashHistory[Hashindex])
end
end
--Mines the BTC pending transaction
local function HashMine(CarID1)
while stringtohash:sub(1,2) ~= "00" do
STRINGTOHASH = stringtohash..HASHNUMBER
stringtohash = HASHLIBRARY.sha256(STRINGTOHASH)
HASHNUMBER = HASHNUMBER + 1
wait(1)
table.insert()
end
HashGUI.Text = stringtohash
PendingTextGui.Text = ""
local CarID1 = CarBought
if CarID1 == 1 then
ConfirmedText.Text = ("Car1 ".. game.Workspace.Cars.Car1Buy.Car1.Value .. "BTC To Malta Car Dealer from " .. Players:GetChildren()[1].Name)
AfterCarPurchase()
elseif CarID1 == 2 then
ConfirmedText.Text = ("Car2 ".. game.Workspace.Cars.Car2Buy.Car2.Value.. "BTC To Malta Car Dealer from " .. Players:GetChildren()[1].Name)
AfterCarPurchase()
elseif CarID1 == 3 then
ConfirmedText.Text = ("Car3 ".. game.Workspace.Cars.Car3Buy.Car3.Value .. "BTC To Malta Car Dealer from " .. Players:GetChildren()[1].Name)
end
AfterCarPurchase()
end
table.insert() will cause the error message
bad argument #1 to 'insert' (table expected, got no value)
According to the Lua 5.4 Reference Manual - table.insert, it is mandatory to provide the table you want to insert to and the value you want to to insert into that table.
table.insert (list, [pos,] value)
Inserts element value at position pos in list, shifting up the
elements list[pos], list[pos+1], ยทยทยท, list[#list]. The default value
for pos is #list+1, so that a call table.insert(t,x) inserts x at the
end of the list t.
If you want to assign a value to a specific table index you need to use indexing assignmet t[key] = value

How can I use a table in LUA for pinging multiple devices and detecting change in variable status

I am trying to ping a number of IP address on a local network at defined intervals and then send a message only when a device connects. I have managed to get it to work for a single device, but when I add additional devices to the table the code fails.
Many thanks in advance.
An earlier version without the table and just a single IP address works perfectly. But adding the table and the "for key,value loop" only works if a single entry is in the table.
local tble = {
["device name"] = "192.168.1.204"
}
for key,value in pairs(tble) do
statuscheckIP=os.execute("arping -f -w 3 " .. value)
if statuscheckIP ~= lastcheckIP then
if statuscheckIP == 0 and lastcheckIP == 256 then
subject ="" ..key.. " , ( IP Address " ..value.. ") Connected"
message = "Connection Alert\nThe device named " ..key.. ", with the IP address " ..value.. " has just connected to the WiFi network"
--send email notification
luup.call_action("urn:upnp-org:serviceId:SmtpNotification1", "SendEmail", { Recipient_Name="SomeOne", Recipient_eMail="someone#somewhere.com", Subject= subject, Message=message }, 24)luup.call_action("urn:upnporg:serviceId:SmtpNotification1","ResetCount",{}, 24)
else
end
end
end
lastcheckIP = statuscheckIP
The code you posted is valid. There are not many reasons why this would fail due to more entries in your table.
os.execute Execute an operating system shell command. This is like the C system() function. The system dependent status code is returned.
Running os.execute will start a arping and return an exitcode. Then you are comparing that statuscheckIP == 0 a lastcheckIP == 256. The if before is redundant. If true you are sending your message and continuing.
After worked though all entries you are setting lastcheckIP to statusCheckIP and this is propably your error. It should be before the last if and inside your loop. But even then does not make sense if 0 is the only correct return code. If lastcheckIP is set to any other value your both if's will never go true again.
Either your last line lastcheckIP = statuscheckIP is wrongly placed, lastcheckIP was never initialized to 256 or you should rethink your whole program.
EDIT:
After understanding the intention of the provided program, I've created a probably working example. This should show you, how to easily use tables in Lua as a structures. I was not able to test the following code.
local WAIT_TIME = 10
local STATUS_CODE_CONNECTED = 0
local STATUS_CODE_NOT_CONNECT = 256 -- not sure about this (return code from arping for failure)
local device_table =
{
["device_name1"] =
{
ip = "<ip address>",
status_code = STATUS_CODE_NOT_CONNECT
},
["device_name1"] =
{
ip = "<ip address>",
status_code = STATUS_CODE_NOT_CONNECT
}
-- , ...
}
while true do
-- check for changed return codes
for device_name, device in pairs(device_table) do
local temp_status_code = os.execute("arping -f -w 3 " .. device.ip)
-- status code changed
if temp_status_code ~= device.status_code then
-- device connected
if temp_status_code == STATUS_CODE_CONNECTED then
local subject = "" .. device_name .. " , ( IP Address " .. device.ip .. ") Connected"
local message = "Connection Alert\nThe device named " .. device_name .. ", with the IP address " .. device.ip .. " has just connected to the WiFi network"
--send email notification
luup.call_action(
"urn:upnp-org:serviceId:SmtpNotification1",
"SendEmail",
{
Recipient_Name = "SomeOne",
Recipient_eMail = "someone#somewhere.com",
Subject = subject,
Message = message
}, 24)
luup.call_action(
"urn:upnporg:serviceId:SmtpNotification1",
"ResetCount",
{ }, 24)
end
-- update last device status_code if changed
device.status_code = temp_status_code
end
end
os.execute("sleep " .. tonumber(WAIT_TIME)) -- wait some time for next check
end
If I've understand you wrongly and you either do not want to have this program run all the time or do not want to have all addresses in a table then you should ask again or somewhere else because that would be out off topic.

Why it gives me Type error in that code?

Why he gives me (Type error) in that statment
" address = cur.fetchone()[2] last = cur.fetchone()[4] no = cur.fetchone()[5] , while it accept "name = cur.fetchone()[1]" in the code : "
import sqlite3
conn = sqlite3.connect('myproject.sqlite')
cur = conn.cursor()
print "Welcome Mr/Hefnawy"
cur.execute('SELECT phone FROM participants')
b = cur.fetchone()[0]
while True:
a = raw_input("Enter Phone number here : ")
if a == b :
cur.execute('SELECT name,address,last_order,no_of_orders FROM participants WHERE phone = ?',(b, ))
name = cur.fetchone()[1]
address = cur.fetchone()[2]
last = cur.fetchone()[4]
no = cur.fetchone()[5]
print "The Costumer is already exist in Paricipants "
print "To edit the costumer data press (1)", "\n" , "to delet the costumer press (2)", "\n" , "add new order to the costumer press (3) "
c = raw_input("Enter your choice here : ")
if c == "1":
print "What do you want to edit ? , to edit name press 1 , to edit address press 2 , to edit phone press 3"
d = raw_input("Enter your choice here : ")
if d == "1" :
e = raw_input("New costumer name please ")
cur.execute('UPDATE participants SET name = ? WHERE phone = ?' , (e , a))
print "Costumer name has been updated to :", e
print ""
conn.commit()
else:
print "The costumer is not exist"
print b
print a , type(a)
When you are fetching something from a cursor say for example
t = cur.fetchone()
you can access the data from t using
print t[0],t[1],t[2] but In your case you are using multiple cur.fetchone() which allows you to use name = cur.fetchone()[1] that ends the data in the cursor. The second line address = cur.fetchone()[2] and the lines that follow it do not have a sql query executed for them to fetch, hence giving you the error. If you want to access the whole row just assign it to a variable and use the variable to get the data.

Use of uninitialized value $end_time1 in string eq .......error in perl

i want to retrive some data from my database,if $end_time1 is null then will be update table ,otherwise will do nothing ,but when i run the code,i found the $end_time1 is null,then will be update the table ,but if not null ,it's will be return the error :
Use of uninitialized value $end_time1 in string eq ........
part of my code :
my $select_sth = $dbh->prepare("SELECT id ,H1, H2, addr1, addr2, time_1, time_2,
end_time_1,end_time_2,count1,count2 FROM service") or die "$dbh->errstr";
$select_sth->execute() or die "$dbh->errstr";
while (my #row_ref = $select_sth->fetchrow_array)
{
my $Rid = $row_ref[0];
my $addr1 = $row_ref[3];
my $addr2 = $row_ref[4];
my $end_time1 = "NULL" unless $row_ref[7];
my $end_time2 = "NULL" unless $row_ref[8];
my $count1 = $row_ref[9];
my $count2 = $row_ref[10];
if($end_time1 eq "NULL")
{
print "$end_time1 is null\n";
$dbh->do ("update service set end_time_1 = '$datetime_now' where id = $Rid");
}
}
please someone what's wrong with my code ?how to fix ?
Your current code only sets $endtime1 if $row_ref[7] is not defined. This means that $endtime1 is undefined if $row_ref[7] does have a value, so you get that Use of uninitialized value $end_time1 in string eq... error when you test it.
Change your code so that $endtime1 will either be set to $row_ref[7] (if it is defined) or to NULL:
my $end_time1 = $row_ref[7] || 'NULL';
Then you can use your existing code:
if ($end_time1 eq "NULL")
{
print "end_time1 is null\n";
$dbh->do ("update service set end_time_1 = '$datetime_now' where id = $Rid");
}
The same issue exists for $endtime2, so you may want to make a similar alteration.
Use defined:
if ( !defined $end_time1 ) {
print "end_time1 is null\n";
}

Drools with eval function rule won't fire

I have the following rule:
rule "AddSource"
when
$model : MFMModel ()
Node( type == "source", funName : name )
$ffs : Structure( ffsName : name )
WholePart( structure == ffsName, ffunction == funName )
eval (Test.checkExsit($model,$ffs))
then
System.out.println( ffsName + ":" + funName);
Source s = new Source( funName );
insert (s);
$ffs.addToStructure( s );
System.out.println(Test.checkExsit($model,$ffs));
end
The rule fires when I delete the eval function in the when part, and the printout says Test.checkExsit($model,$ffs) return true.
But with the eval function, the rule will never fire.
Anyone knows what the problem is?

Resources