How to get "android.provider.ContactsContract.Contacts" field in Luaj - luaj

I use Lua Interpreter to get information for my iGO navigator and I need to get some fields from android.provider.ContactsContract.Contacts
I got successfully
cntr = luajava.bindClass("android.provider.ContactsContract")
and I try to get Contacts
cntct = cntr.Contacts
or
cntct = luajava.bindClass("android.provider.ContactsContract.Contacts")
No success
Basically I need to get result as there
Intent pickIntent = new Intent(Intent.ACTION_PICK,
android.provider.ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(pickIntent, PICK_RESULT);

This is an answer to myself. Ofcourse you need to have permission in the manifest.
cr = activity:getContentResolver()
contacts = luajava.bindClass("android.provider.ContactsContract")
build = luajava.bindClass("android.os.Build")
D_Name = build.VERSION.SDK_INT >= build.VERSION_CODES.HONEYCOMB and contacts.Contacts.DISPLAY_NAME_PRIMARY or contacts.Contacts.DISPLAY_NAME
--str = luajava.bindClass("java.lang.String")
cur = cr:query(contacts.Contacts.CONTENT_URI)
local count = cur and cur:getCount() or -1
print(count)
if cur and count > 0 then
--local name, id, pCur, phoneNo
while cur:moveToNext() do
id = cur:getString(cur:getColumnIndex(contacts.Contacts._ID))
name = cur:getString(cur:getColumnIndex(D_Name))
--print("id: " .. id, "name: " .. name)
if cur:getInt(cur:getColumnIndex(contacts.Contacts.HAS_PHONE_NUMBER)) > 0 then
--str_str = luajava.newInstance( "java.lang.String", id )
-- str_array = luajava.newInstance( "java.lang.reflect.Array", ({str_str}) )
pCur = cr:query(contacts.CommonDataKinds.Phone.CONTENT_URI, nil, contacts.CommonDataKinds.Phone.CONTACT_ID .. " = ?", ({id}), nil)
print(pCur:getCount())
while pCur:moveToNext() do
phoneNo = pCur:getString(pCur:getColumnIndex(contacts.CommonDataKinds.Phone.NUMBER))
print("Name: " .. name, "Phone Number: " .. phoneNo)
end
pCur:close()
end
--if cur:getInt(cur:getColumnIndex(contacts.Contacts.HAS_EMAIL_DATA)) > 0 then
--str_str = luajava.newInstance( "java.lang.String", id )
-- str_array = luajava.newInstance( "java.lang.reflect.Array", ({str_str}) )
pCur = cr:query(contacts.CommonDataKinds.Email.CONTENT_URI, nil, contacts.CommonDataKinds.Email.CONTACT_ID .. " = ?", ({id}), nil)
print(pCur:getCount())
if pCur then
while pCur:moveToNext() do
Email_data = pCur:getString(pCur:getColumnIndex(contacts.CommonDataKinds.Email.DATA))
print("Name: " .. name, "Email_data: " .. Email_data)
end
end
pCur:close()
pCur = cr:query(contacts.Data.CONTENT_URI, nil, contacts.Data.CONTACT_ID .. " = " .. id)
print(pCur:getCount())
if pCur then
while pCur:moveToNext() do
skype_type = pCur:getInt(pCur:getColumnIndex(contacts.CommonDataKinds.Im.PROTOCOL))
print(skype_type, contacts.CommonDataKinds.Im.PROTOCOL_SKYPE)
if contacts.CommonDataKinds.Im.PROTOCOL_SKYPE == skype_type then
imName = pCur:getString(pCur:getColumnIndex(contacts.CommonDataKinds.Im.DATA))
print("Name: " .. name, "skype_type: " .. skype_type .. "imName: " .. imName)
end
end
end
pCur:close()
--end
end
end
if cur then
cur:close()
end

Related

ERROR - attempt to perform arithmetic on a nil value

I have the following error when opening my garage in fivem,
and also the cars don't show up in my garage.
enter image description here
The error says line 692
status = "<span class=\"green\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
full code
`
function src.myVehicles(work)
local source = source
local user_id = vRP.getUserId(source)
local myvehicles = {}
local ipva = ""
local status = ""
if user_id then
if workgarage[work] then
for k,v in pairs(workgarage) do
if k == work then
for k2,v2 in pairs(v) do
status = "<span class=\"green\">"..k.."</span>"
ipva = "<span class=\"green\">Pago</span>"
table.insert(myvehicles,{ name = v2, name2 = vRP.vehicleName(v2), engine = 100, body = 100, fuel = 100, status = status, ipva = ipva })
end
end
end
return myvehicles
else
local vehicle = vRP.query("creative/get_vehicle",{ user_id = parseInt(user_id) })
local address = vRP.query("homes/get_homeuserid",{ user_id = parseInt(user_id) })
if #address > 0 then
for k,v in pairs(address) do
if v.home == work then
for k2,v2 in pairs(vehicle) do
if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then
status = "<span class=\"red\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>" --0.5
elseif vehicle[k2].detido == 1 then
status = "<span class=\"orange\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
else
status = "<span class=\"green\">Gratuita</span>"
end
if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then
ipva = "<span class=\"red\">Atrasado</span>"
else
ipva = "<span class=\"green\">Pago</span>"
end
table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva })
end
return myvehicles
else
for k2,v2 in pairs(vehicle) do
if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then
status = "<span class=\"red\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
elseif vehicle[k2].detido == 1 then
status = "<span class=\"orange\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
else
status = "<span class=\"green\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.005)).."</span>"
end
if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then
ipva = "<span class=\"red\">Atrasado</span>"
else
ipva = "<span class=\"green\">Pago</span>"
end
table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva })
end
return myvehicles
end
end
else
for k2,v2 in pairs(vehicle) do
if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then
status = "<span class=\"red\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
elseif vehicle[k2].detido == 1 then
status = "<span class=\"orange\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
else
status = "<span class=\"green\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
end
if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then
ipva = "<span class=\"red\">Atrasado</span>"
else
ipva = "<span class=\"green\">Pago</span>"
end
table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva })
end
return myvehicles
end
end
end
end
`
I tried several things but I couldn't solve it.
in the database I have 2 cars assigned to me, but they still don't appear in my garage.

Returning values in lua

function SearchDatabase(ply, value)
local id = ply:SteamID()
if id == nil then return end
local query = ECLIPSEUSERDATA:query("SELECT " .. value .. " FROM main WHERE usersteamid = '" .. id .. "';")
if not query then return end
query.onData = function(q, d)
if(#query:getData() >= 1)then
print("[SQL]" .. value .. " = " .. tostring(d[value]))
print(tostring(d[value]))
return tostring(d[value])
end
end
query.onError = function(db, err)
print("[SQL] Failed to search database - Error: ", err)
end
query:start()
query:wait()
end
function UpdatePlaytime(ply)
if ply == nil then
return
end
local PlayersPlaytime = SearchDatabase(ply, "playtime")
print(PlayersPlaytime)
local PlaytimeUpdate = PlayersPlaytime + 1
end
The problem i'm currently having is when the value: d[value], is returned to my function UpdatePlaytime() function it is returning a nil value and I have no idea how to fix it.
Console logs:
[SQL]playtime = 0
0
nil
Any help will appreciated thanks!
-D12

what`s wrong with 'iup.config' in iup package on lua

I started to learn lua (version 5.1) plus iup (version 3.5) library, but this issue shut me down :(
So, the clearest example from iup tutorial http://webserver2.tecgraf.puc-rio.br/iup/en/tutorial/tutorial3.html#Recent_Config
require("iuplua")
require("iupluaimglib")
--********************************** Utilities *****************************************
function str_find(str, str_to_find, casesensitive, start)
if (not casesensitive) then
return str_find(string.lower(str), string.lower(str_to_find), true, start)
end
return string.find(str, str_to_find, start, true)
end
function read_file(filename)
local ifile = io.open(filename, "r")
if (not ifile) then
iup.Message("Error", "Can't open file: " .. filename)
return nil
end
local str = ifile:read("*a")
if (not str) then
iup.Message("Error", "Fail when reading from file: " .. filename)
return nil
end
ifile:close()
return str
end
function write_file(filename, str)
local ifile = io.open(filename, "w")
if (not ifile) then
iup.Message("Error", "Can't open file: " .. filename)
return false
end
if (not ifile:write(str)) then
iup.Message("Error", "Fail when writing to file: " .. filename)
end
ifile:close()
return true
end
--********************************** Main (Part 1/2) *****************************************
-- it`s there:
config = iup.config{} ------ here it is, first error
config.app_name = "simple_notepad"
config:Load()
lbl_statusbar = iup.label{title = "Lin 1, Col 1", expand = "HORIZONTAL", padding = "10x5"}
multitext = iup.text{
multiline = "YES",
expand = "YES"
}
font = config:GetVariable("MainWindow", "Font")
if (font) then
multitext.font = font
end
item_open = iup.item{title = "&Open...\tCtrl+O"}
item_saveas = iup.item{title="Save &As...\tCtrl+S"}
item_font = iup.item{title="&Font..."}
item_about = iup.item{title="&About..."}
item_find = iup.item{title="&Find...\tCtrl+F"}
item_goto = iup.item{title="&Go To..."}
item_exit = iup.item{title="E&xit"}
--********************************** Callbacks *****************************************
function config:recent_cb()
local filename = self.title
local str = read_file(filename)
if (str) then
multitext.value = str
end
end
function multitext:caret_cb(lin, col)
lbl_statusbar.title = "Lin "..lin..", Col "..col
end
function item_open:action()
local filedlg = iup.filedlg{
dialogtype = "OPEN",
filter = "*.txt",
filterinfo = "Text Files",
parentdialog=iup.GetDialog(self)
}
filedlg:popup(iup.CENTERPARENT, iup.CENTERPARENT)
if (tonumber(filedlg.status) ~= -1) then
local filename = filedlg.value
local str = read_file(filename)
if (str) then
config:RecentUpdate(filename)
multitext.value = str
end
end
filedlg:destroy()
end
function item_saveas:action()
local filedlg = iup.filedlg{
dialogtype = "SAVE",
filter = "*.txt",
filterinfo = "Text Files",
parentdialog=iup.GetDialog(self)
}
filedlg:popup(iup.CENTERPARENT, iup.CENTERPARENT)
if (tonumber(filedlg.status) ~= -1) then
local filename = filedlg.value
if (write_file(filename, multitext.value)) then
config:RecentUpdate(filename)
end
end
filedlg:destroy()
end
function item_exit:action()
config:DialogClosed(iup.GetDialog(self), "MainWindow")
config:Save()
config:destroy()
return iup.CLOSE
end
function item_goto:action()
local line_count = multitext.linecount
local lbl_goto = iup.label{title = "Line Number [1-"..line_count.."]:"}
local txt_goto = iup.text{mask = iup.MASK_UINT, visiblecolumns = 20} --unsigned integer numbers only
local bt_goto_ok = iup.button{title = "OK", text_linecount = 0, padding = "10x2"}
bt_goto_ok.text_linecount = line_count
function bt_goto_ok:action()
local line_count = tonumber(self.text_linecount)
local line = tonumber(txt_goto.value)
if (line < 1 or line >= line_count) then
iup.Message("Error", "Invalid line number.")
return
end
goto_dlg.status = 1
return iup.CLOSE
end
local bt_goto_cancel = iup.button{title = "Cancel", padding = "10x2"}
function bt_goto_cancel:action()
goto_dlg.status = 0
return iup.CLOSE
end
local box = iup.vbox{
lbl_goto,
txt_goto,
iup.hbox{
iup.fill{},
bt_goto_ok,
bt_goto_cancel,
normalizesize="HORIZONTAL",
},
margin = "10x10",
gap = "5",
}
goto_dlg = iup.dialog{
box,
title = "Go To Line",
dialogframe = "Yes",
defaultenter = bt_goto_ok,
defaultesc = bt_goto_cancel,
parentdialog = iup.GetDialog(self)
}
goto_dlg:popup(iup.CENTERPARENT, iup.CENTERPARENT)
if (tonumber(goto_dlg.status) == 1) then
local line = txt_goto.value
local pos = iup.TextConvertLinColToPos(multitext, line, 0)
multitext.caretpos = pos
multitext.scrolltopos = pos
end
goto_dlg:destroy()
end
function item_find:action()
local find_dlg = self.find_dialog
if (not find_dlg) then
local find_txt = iup.text{visiblecolumns = "20"}
local find_case = iup.toggle{title = "Case Sensitive"}
local bt_find_next = iup.button{title = "Find Next", padding = "10x2"}
local bt_find_close = iup.button{title = "Close", padding = "10x2"}
function bt_find_next:action()
local find_pos = tonumber(find_dlg.find_pos)
local str_to_find = find_txt.value
local casesensitive = (find_case.value == "ON")
-- test again, because it can be called from the hot key
if (not str_to_find or str_to_find:len()==0) then
return
end
if (not find_pos) then
find_pos = 1
end
local str = multitext.value
local pos, end_pos = str_find(str, str_to_find, casesensitive, find_pos)
if (not pos) then
pos, end_pos = str_find(str, str_to_find, casesensitive, 1) -- try again from the start
end
if (pos) and (pos > 0) then
pos = pos - 1
find_dlg.find_pos = end_pos
iup.SetFocus(multitext)
multitext.selectionpos = pos..":"..end_pos
local lin, col = iup.TextConvertPosToLinCol(multitext, pos)
local pos = iup.TextConvertLinColToPos(multitext, lin, 0) -- position at col=0, just scroll lines
multitext.scrolltopos = pos
else
find_dlg.find_pos = nil
iup.Message("Warning", "Text not found.")
end
end
function bt_find_close:action()
iup.Hide(iup.GetDialog(self)) -- do not destroy, just hide
end
box = iup.vbox{
iup.label{title = "Find What:"},
find_txt,
find_case,
iup.hbox{
iup.fill{},
bt_find_next,
bt_find_close,
normalizesize="HORIZONTAL",
},
margin = "10x10",
gap = "5",
}
find_dlg = iup.dialog{
box,
title = "Find",
dialogframe = "Yes",
defaultenter = bt_next,
defaultesc = bt_close,
parentdialog = iup.GetDialog(self)
}
-- Save the dialog to reuse it
self.find_dialog = find_dlg -- from the main dialog */
end
-- centerparent first time, next time reuse the last position
find_dlg:showxy(iup.CURRENT, iup.CURRENT)
end
function item_font:action()
local font = multitext.font
local fontdlg = iup.fontdlg{value = font, parentdialog=iup.GetDialog(self)}
fontdlg:popup(iup.CENTERPARENT, iup.CENTERPARENT)
if (tonumber(fontdlg.status) == 1) then
multitext.font = fontdlg.value
config:SetVariable("MainWindow", "Font", fontdlg.value)
end
fontdlg:destroy()
end
function item_about:action()
iup.Message("About", " Simple Notepad\n\nAutors:\n Gustavo Lyrio\n Antonio Scuri")
end
--********************************** Main (Part 2/2) *****************************************
recent_menu = iup.menu{}
file_menu = iup.menu{
item_open,
item_saveas,
iup.separator{},
iup.submenu{title="Recent &Files", recent_menu},
item_exit
}
edit_menu = iup.menu{item_find, item_goto}
format_menu = iup.menu{item_font}
help_menu = iup.menu{item_about}
sub_menu_file = iup.submenu{file_menu, title = "&File"}
sub_menu_edit = iup.submenu{edit_menu, title = "&Edit"}
sub_menu_format = iup.submenu{format_menu, title = "F&ormat"}
sub_menu_help = iup.submenu{help_menu, title = "&Help"}
menu = iup.menu{
sub_menu_file,
sub_menu_edit,
sub_menu_format,
sub_menu_help,
}
btn_open = iup.button{image = "IUP_FileOpen", flat = "Yes", action = item_open.action, canfocus="No", tip = "Open (Ctrl+O)"}
btn_save = iup.button{image = "IUP_FileSave", flat = "Yes", action = item_saveas.action, canfocus="No", tip = "Save (Ctrl+S)"}
btn_find = iup.button{image = "IUP_EditFind", flat = "Yes", action = item_find.action, canfocus="No", tip = "Find (Ctrl+F)"}
toolbar_hb = iup.hbox{
btn_open,
btn_save,
iup.label{separator="VERTICAL"},
btn_find,
margin = "5x5",
gap = 2,
}
vbox = iup.vbox{
toolbar_hb,
multitext,
lbl_statusbar,
}
dlg = iup.dialog{
vbox,
title = "Simple Notepad",
size = "HALFxHALF",
menu = menu,
close_cb = item_exit.action,
}
function dlg:k_any(c)
if (c == iup.K_cO) then
item_open:action()
elseif (c == iup.K_cS) then
item_saveas:action()
elseif (c == iup.K_cF) then
item_find:action()
elseif (c == iup.K_cG) then
item_goto:action()
end
end
config:RecentInit(recent_menu, 10)
-- parent for pre-defined dialogs in closed functions (IupMessage)
iup.SetGlobal("PARENTDIALOG", iup.SetHandleName(dlg))
config:DialogShow(dlg, "MainWindow")
-- to be able to run this script inside another context
if (iup.MainLoopLevel()==0) then
iup.MainLoop()
iup.Close()
end
don`t working:
error output:
wlua: source.wlua:52: attempt to call field 'config' (a nil value)
So, why it isn`t working?

StackExchange.Redis Lua script error in for loop

I am facing a problem with the Lua script (please find it below) in the StackExchange.Redis.
I have dissected the code and got all of it working except for the last loop.
I get the following as error -- ERR Protocol error: expected '$', got ' '
The error message is quite generic in nature, as it gives me the same error message for different types of errors.
Can someone help me to figure out the problem?
var doesExist = (bool)db.ScriptEvaluate(#"
local function isDateInRange(DateStart, DateEnd, GivenDate)
if (GivenDate > DateStart and GivenDate < DateEnd)
then
return(true)
else
return(false)
end
end
--Fetch User's Category's StartDate and EndDate
local function IsCategoryDateValid()
local givenDate, DateStart, DateEnd
GivenDate = '2017-01-09'
StartDate = '2015-01-01'
EndDate = '2018-01-01'
local isDateValid
isDateValid = isDateInRange(StartDate, EndDate, GivenDate)
return(isDateValid)
end
-- Pass User, UserCategory and UserCategoryItem as parameters
local userNameKey = 'UserDetails:Invincible'
local userCategoryKey = 'UserCategories:Book'
local userCategoryItemKey = 'UserCategoryItems:Harry-Potter'
local userNameKeySplit = {}
local a = 1
for i in string.gmatch(userNameKey, '([^'..':'..']+)') do
userNameKeySplit[a] = i
a = a + 1
end
local userName = userNameKeySplit[2]
local userCategoryKeySplit = {}
local b = 1
for j in string.gmatch(userCategoryKey, '([^'..':'..']+)') do
userCategoryKeySplit[b] = j
b = b + 1
end
local userCategory = userCategoryKeySplit[2]
local userCategoryItemKeySplit = {}
local c = 1
for k in string.gmatch(userCategoryItemKey, '([^'..':'..']+)') do
userCategoryItemKeySplit[c] = k
c = c + 1
end
local userCategoryItem = userCategoryItemKeySplit[2]
-- Fetch Users, UserCategories and UserCategoryItems from the Redis DB
local userData = {'Invincible', 'User1', 'User2', 'User3'}
local userCategoryData = {'Book', 'Movie', 'Journals'}
local userCategoryItemData = {'Hardy-Boys', 'Harry-Potter', 'Shawshank-Redemption', 'The-Terminal'}
local msg
for i=1,#userData,1
do
if(userData[i] == userName)
then
for j=1,#userCategoryData,1
do
if(userCategoryData[j] == userCategory)
then
msg = true
break
else
msg = false
end
end
break
else
msg = false
break
end
end
return msg
",
new RedisKey[] { "UserDetails:" + "Invincible", "UserCategories:" + "Book", "UserCategoryItems:" + "Harry-Potter" });

"Error: attempt to index local 'self' (a nil value)" in string.split function

Quick facts, I got this function from http://lua-users.org/wiki/SplitJoin at the very bottom, and am attempting to use it in the Corona SDK, though I doubt that's important.
function string:split(sSeparator, nMax, bRegexp)
assert(sSeparator ~= '')
assert(nMax == nil or nMax >= 1)
local aRecord = {}
if self:len() > 0 then
local bPlain = not bRegexp
nMax = nMax or -1
local nField=1 nStart=1
local nFirst,nLast = self:find(sSeparator, nStart, bPlain)
while nFirst and nMax ~= 0 do
aRecord[nField] = self:sub(nStart, nFirst-1)
nField = nField+1
nStart = nLast+1
nFirst,nLast = self:find(sSeparator, nStart, bPlain)
nMax = nMax-1
end
aRecord[nField] = self:sub(nStart)
end
return aRecord
end
The input: "1316982303 Searching server"
msglist = string.split(msg, ' ')
Gives me the error in the title. Any ideas? I'm fairly certain it's just the function is out of date.
Edit: lots more code
Here's some more from the main.lua file:
multiplayer = pubnub.new({
publish_key = "demo",
subscribe_key = "demo",
secret_key = nil,
ssl = nil, -- ENABLE SSL?
origin = "pubsub.pubnub.com" -- PUBNUB CLOUD ORIGIN
})
multiplayer:subscribe({
channel = "MBPocketChange",
callback = function(msg)
-- MESSAGE RECEIVED!!!
print (msg)
msglist = string.split(msg, ' ')
local recipient = msglist[0] --Get the value
table.remove(msglist, 0) --Remove the value from the table.
local cmdarg = msglist[0]
table.remove(msglist, 0)
arglist = string.split(cmdarg, ',')
local command = arglist[0]
table.remove(arglist, 0)
argCount = 1
while #arglist > 0 do
argname = "arg" .. argCount
_G[argname] = arglist[0]
table.remove(arglist, 0)
argCount = argCount + 1
end
Server.py:
This is the multiplayer server that sends the necessary info to clients.
import sys
import tornado
import os
from Pubnub import Pubnub
## Initiat Class
pubnub = Pubnub( 'demo', 'demo', None, False )
## Subscribe Example
def receive(message) :
test = str(message)
msglist = test.split()
recipient = msglist.pop(0)
msg = msglist.pop(0)
id = msglist.pop(0)
if id != "server":
print id
print msg
commandHandler(msg,id)
return True
def commandHandler(cmd,id):
global needOp
needOp = False
global matchListing
if server is True:
cmdArgList = cmd.split(',')
cmd = cmdArgList.pop(0)
while len(cmdArgList) > 0:
argument = 1
locals()["arg" + str(argument)] = cmdArgList.pop(0)
argument += 1
if cmd == "Seeking":
if needOp != False and needOp != id:
needOp = str(needOp)
id = str(id)
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : needOp + " FoundOp," + id + " server"
})
print ("Attempting to match " + id + " with " + needOp + ".")
needOp = False
matchListing[needOp] = id
else:
needOp = id
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : id + ' Searching server'
})
print "Finding a match for: " + id
elif cmd == "Confirm":
if matchListing[id] == arg1:
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : arg1 + ' FoundCOp,' + id + ' server'
})
matchListing[arg1] = id
else:
pass #Cheater.
elif cmd == "SConfirm":
if matchListing[id] == arg1 and matchListing[arg1] == id:
os.system('python server.py MBPocketChange' + arg1)
#Here, the argument tells both players what room to join.
#The room is created from the first player's ID.
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : id + ' GameStart,' + arg1 + ' server'
})
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : arg1 + ' GameStart,' + arg1 + ' server'
})
else:
pass #hax
else:
pass
def connected():
pass
try:
channel = sys.argv[1]
server = False
print("Listening for messages on '%s' channel..." % channel)
pubnub.subscribe({
'channel' : channel,
'connect' : connected,
'callback' : receive
})
except:
channel = "MBPocketChange"
server = True
print("Listening for messages on '%s' channel..." % channel)
pubnub.subscribe({
'channel' : channel,
'connect' : connected,
'callback' : receive
})
tornado.ioloop.IOLoop.instance().start()
This error message happens if you run:
string.split(nil, ' ')
Double check your inputs to be sure you are really passing in a string.
Edit: in particular, msglist[0] is not the first position in the array in Lua, Lua arrays start at 1.
As an aside, this function was written when the intention that you'd use the colon syntactic sugar, e.g.
msglist=msg:split(' ')

Resources