I don't have any errors.
My scrips can take the name of new weapon but it cant check equal of hololink_swep.
The print of equal doesn't appear.
Please help.
My code:
hook.Add( "PlayerSwitchWeapon", function( ply, oldWeapon, newWeapon )
print( "Your new weapon is " .. newWeapon:GetClass() .. "." );
if ( newWeapon == hololink_swep ) then
print( "This weapon is speciall" .. newWeapon:GetClass() .. "." );
end
end );
if (tostring(newWeapon) == tostring(hololink_swep) )
hook.Add("PlayerSwitchWeapon", "some name of hook", function(ply, oldWeapon, newWeapon)
print("Your new weapon is " .. newWeapon:GetClass() .. ".")
if (newWeapon == "hololink_swep") then
print("This weapon is speciall" .. newWeapon:GetClass() .. ".")
end
end)
also do not forget to name your hook. I named it for example some name of hook.
Related
I'm working on a project where I want to update the clock on screen say every 5 seconds unless the user inputs something. This is the code I have so far,
function thread1()
term.clear()
term.setCursorPos(1,1)
write (" SteveCell ")
local time = os.time()
local formatTime = textutils.formatTime(time, false)
write (formatTime)
print ("")
print ("")
for i=1,13 do
write ("-")
end
print("")
print ("1. Clock")
print ("2. Calender")
print ("3. Memo")
print ("4. Shutdown")
for i=1,13 do
write ("-")
end
print ("")
print ("")
write ("Choose an option: ")
local choice = io.read()
local choiceValid = false
if (choice == "1") then
-- do this
elseif (choice == "2") then
-- do that
elseif (choice == "3") then
-- do this
elseif (choice == "4") then
shell.run("shutdown")
else
print ("Choice Invalid")
os.sleep(2)
shell.run("mainMenu")
end
end
function thread2()
localmyTimer = os.startTimer(5)
while true do
local event,timerID = os.pullEvent("timer")
if timerID == myTimer then break end
end
return
end
parallel.waitForAny(thread1, thread2)
shell.run("mainMenu")
Unfortunately it's not working. If someone could help me with this, I would really appreciate it. Thanks :)
You want to do something like this (Im not doing the correct on screen drawing, only the time)
local function thread1_2()
-- both threads in one!
while true do
local ID_MAIN = os.startTimer(5)
local ID = os.startTimer(0.05)
local e = { os.pullEvent() }
if e[1] == "char" then
-- Check all the options with variable e[2] here
print( string.format( "Pressed %s", e[2] ) )
break -- Getting out of the 'thread'
elseif e[1] == "timer" and e[2] == ID then
ID = os.startTimer(0.05) -- shortest interval in cc
redrawTime() -- Redraw and update the time in this function!!!
elseif e[1] == "timer" and e[2] == MAIN_ID then
break
end
end
end
Also, ask this in the proper forum, you have more chance getting an answer there!
Another note, get more into event handling, it really helps.
FYI Lua doesn't have 'multi-threading' as in executing multiple routines simultaneously. What it does have is 'thread parking.' You can switch between routines (yielding) and switch back and it will resume where it left off, but only a single routine will be active at any given time.
This is my go-to Lua reference, which explains in detail:
http://lua-users.org/wiki/CoroutinesTutorial
Okay I am working on a script for my Oxide Lua Plugin, and I am also just learning Lua Script so I am not real sure how to do this.
-- *******************************************
-- Broadcasts a Server Notification
-- *******************************************
function PLUGIN:cmdNotice( netuser, args )
table.concat(args," ")
local allnetusers = rust.GetAllNetUsers()
if (allnetusers) then
for i=1, #allnetusers do
local netuser = allnetusers[i]
rust.Notice(netuser, args[1]))
rust.SendChatToUser(netuser, "Message Sent:" .. args[1])
end
end
end
What I am trying to do is fix this so I do not have to manually encase my notice in "".
For example, as the code stands, while I am in game in rust if I use the /notice command I have two outcomes.
Example 1
/notice hello everone
will only produce
hello
but if I do
/notice "hello everyone"
will give the entire message. So I am a little confused.
So my new code should look like this
-- *******************************************
-- Broadcasts a Server Notification
-- *******************************************
function PLUGIN:cmdNotice( netuser, args )
table.concat(args," ")
local allnetusers = rust.GetAllNetUsers()
if (allnetusers) then
for i=1, #allnetusers do
local netuser = allnetusers[i]
rust.Notice(netuser, table.concat(args, " " ))
rust.SendChatToUser(netuser, "Message Sent:" .. table.concat(args, " "))
end
end
end
Edit 3/15/2014
Okay cool so in a since I can also do this as well correct?
function PLUGIN:cmdNotice( netuser, args )
if (not args[1]) then
rust.Notice( netuser, "Syntax: /notice Message" )
return
end
local allnetusers = rust.GetAllNetUsers()
if allnetusers then
for i=1, #allnetusers do
local netuser = allnetusers[i]
local notice_msg = table.concat(args," ")
rust.Notice(netuser, notice_msg)
rust.SendChatToUser(netuser, "Message Sent:" .. notice_msg)
end
end
end
To clarify what #EgorSkriptunoff said, table.concat returns the joined table, but it does not change the value of args. Since you don't save the joined return value, your line 1 inside the function is useless. As an alternative to his approach, you could do rust.SendChatToUser ( netuser, "Message Sent:" .. table.concat(args, " " ).
My guess is that you were thinking (?) that the joined strings would be saved in the args table as the first item in the table? That's not what happens. The table itself remains unchanged, so when you print args[1], you get only the first string of the array. It "works" when you quote the message because in that case the entire message goes in as one thing, and the array only has an arg[1].
Here's what is going on
t = { "hello", "I", "must", "be", "going"}
-- Useless use of concat since I don't save the return value or use it
table.concat(t, " ")
print(t) -- Still an unjoined table
print(t[1]) -- Prints only "hello"
print(table.concat(t, " ")) -- Now prints the return value
Edit: In response to the follow-up question, see my comments in the code below:
function PLUGIN:cmdNotice( netuser, args )
table.concat(args," ") -- This line is not needed.
local allnetusers = rust.GetAllNetUsers()
-- Lua doesn't count 0 as false, so the line below probably doesn't do
-- what you think it does. If you want to test whether a table has more
-- than 0 items in it, use this:
-- if #allnetusers > 0 then...
if allnetusers then
for i=1, #allnetusers do
local netuser = allnetusers[i]
rust.Notice(netuser, table.concat(args, " " ))
rust.SendChatToUser(netuser, "Message Sent:" .. table.concat(args, " "))
end
end
end
I'v tested & uploaded my app on appStore it's inapp purchases was working perfectly fine, I was able to restore the app too.
But now I want to test it's version 2 but now am able to buy but restore isn't working.
module(..., package.seeall)
require("store")
require("ui")
local inappfile = require("inappfile")
local validProducts, invalidProducts = {}, {}
local listOfProducts =
{
-- These Product IDs must already be set up in your store
-- We'll use this list to retrieve prices etc. for each item
-- Note, this simple test only has room for about 4 items, please adjust accordingly
-- The iTunes store will not validate bad Product IDs
"com.tinytapps.pandamath.fullpack",
}
-------------------------------------------------
-- we store everything inside this group at the end
local newActivity = display.newGroup()
-----------------------------------------------------
---------------- IN APP CODE STARTS HERE ------------------
checkIfPurchased = function()
local filePath = system.pathForFile( "purchased.txt", system.DocumentsDirectory )
local file = io.open( filePath, "r" )
if file then
_G["isPurchased"] = true
--AdMediator.hide()
else
_G["isPurchased"] = false
--local_configuration()
end
end
callforpurchase = function()
if _G["isPurchased"] == false then
local cerateFile = function()
_G.noOfQuestionCompleted=0
local filePath = system.pathForFile( "purchased.txt", system.DocumentsDirectory )
local file = io.open( filePath, "r" )
print(file)
if file then
_G["isPurchased"] = true
io.close( file )
else
file = io.open( filePath, "w" )
_G["isPurchased"] = true
io.close( file )
end
end
function showTitle()
if isSimulator then
local myAlert = native.showAlert( "iTunes Store not available in Corona Simulator",
"Offline testing: see console for output.",
{ "OK" } )
end
end
-------------------------------------------------------------------------------
-- Product IDs should match the In App Purchase products set up in iTunes Connect.
-- We cannot get them from the iTunes store so here they are hard coded;
-- your app could obtain them dynamically from your server.
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Process and display product information obtained from store.
-- Constructs a button for each item
-------------------------------------------------------------------------------
function unpackValidProducts()
local buttonSpacing = 5
-- Utility to build a buy button
-- Handler for buy button
function newBuyButton (index)
local buttonDefault = "add/buybtn.png"
local buttonOver = "add/buybtn.png"
local buyThis = function ( product )
print ("Purchasing " ..product)
-- Purchase the item
if store.canMakePurchases then
store.purchase( {product} )
else
native.showAlert("Store purchases are not available, please try again later",
{ "OK" } )
end
end
function buyThis_closure ( index )
-- Closure wrapper for buyThis() to remember which button
return function ( event )
buyThis (validProducts[index].productIdentifier)
return true
end
end
local hideDescription = function ( )
--descriptionArea.text = "Select a product..."
end
local describeThis = function ( description )
print ("About this product: " ..description)
end
function describeThis_closure ( index )
-- Closure wrapper for describeThis() to remember which button
return function ( event )
describeThis (validProducts[index].description)
return true
end
end
buyButton = ui.newButton{
default = buttonDefault, over = buttonOver,
onPress = describeThis_closure (index), onRelease = buyThis_closure (index),
}
_G.buyButton=buyButton
return buyButton
end
-- Utility to build a restore button
function newRestoreButton ()
local buttonDefault = "add/restorebtn.png"
local buttonOver = "add/restorebtn.png"
local restore = function ( product )
-- Ask the iTunes Store to initiate restore transaction sequence
print ("Restoring " )
store.restore()
end
local hideDescription = function ( )
--descriptionArea.text = "Select a product..."
end
local describeThis = function ()
-- Display info in description area
print ("Test restore feature")
end
--local label = "Test restore"
restoreButton = ui.newButton{
default = buttonDefault, over = buttonOver,
onPress = describeThis, onRelease = restore,
}
_G.restoreButton = restoreButton
return restoreButton
end
print ("Loading product list")
if not validProducts then
native.showAlert( "In App features not available", "initStore() failed", { "OK" } )
else
print ("Product list loaded")
print( "Country: " .. system.getPreference( "locale", "country" ) )
local buttonSpacing = 5
print( "Found " .. #validProducts .. " valid items ")
-- display the valid products in buttons
for i=1, #validProducts do
-- Debug: print out product info
print ("Item " .. i .. ": " .. validProducts[i].productIdentifier
.. " (" .. validProducts[i].price .. ")")
print (validProducts[i].title .. ", ".. validProducts[i].description)
---------------------------------------------------------------------------
-- create and position product button
local myButton = newBuyButton(i)
myButton.x = 570 --centerX - 200
myButton.y = 450 --centerY + 250
--myButton.xScale = 0.6
--myButton.yScale = 0.6
--newActivity:insert(buyButton)
myButton:toFront()
end
local restoreButton = newRestoreButton()
restoreButton.x = 200 --centerX + 200
restoreButton.y = 450 -- centerY + 250
--restoreButton.xScale = 0.6
--restoreButton.yScale = 0.6
--newActivity:insert(restoreButton)
restoreButton:toFront()
for i=1, #invalidProducts do
-- Debug: display the product info
native.showAlert( "Item " .. invalidProducts[i] .. " is invalid.",
{ "OK" } )
print("Item " .. invalidProducts[i] .. " is invalid.")
end
end
end
-------------------------------------------------------------------------------
-- Handler to receive product information
-- This callback is set up by store.loadProducts()
-------------------------------------------------------------------------------
function loadProductsCallback( event )
-- Debug info for testing
print("In loadProductsCallback()")
print("event, event.name", event, event.name)
print(event.products)
print("#event.products", #event.products)
io.flush() -- remove for production
-- save for later use
validProducts = event.products
invalidProducts = event.invalidProducts
unpackValidProducts ()
end
-------------------------------------------------------------------------------
-- Handler for all store transactions
-- This callback is set up by store.init()
-------------------------------------------------------------------------------
function transactionCallback( event )
local infoString
print("transactionCallback: Received event ", event.name)
if event.transaction.state == "purchased" then
cerateFile()
_G["isPurchased"] = true
--AdMediator.hide()
if buyButton ~= nil then
buyButton=nil
end
if restoreButton ~= nil then
restoreButton=nil
end
infoString = "Transaction successful!"
print (infoString)
inappfile.onClose()
print("transactionCallback() method called inappfile.onClose()")
elseif event.transaction.state == "restored" then
print ("Success! Product restored")
cerateFile()
_G["isPurchased"] = true
if buyButton ~= nil then
buyButton=nil
end
if restoreButton ~= nil then
restoreButton=nil
end
infoString = "Transaction successful!"
print (infoString)
inappfile.onClose()
print("transactionCallback() method called inappfile.onClose()")
elseif event.transaction.state == "cancelled" then
infoString = "Transaction cancelled by user."
elseif event.transaction.state == "failed" then
infoString = "Transaction failed, type: ",
event.transaction.errorType, event.transaction.errorString
else
infoString = "Unknown event"
end
-- Tell the store we are done with the transaction.
-- If you are providing downloadable content, do not call this until
-- the download has completed.
store.finishTransaction( event.transaction )
end
-------------------------------------------------------------------------------
-- Setter upper
-------------------------------------------------------------------------------
function setupMyStore (event)
store.loadProducts( listOfProducts, loadProductsCallback )
print ("After store.loadProducts, waiting for callback")
if isSimulator then
-- No Store, so no callbacks, so exercise our GUI "manually"
validProducts[1] = {}
validProducts[1].title = "Panda Math"
validProducts[1].description = "A wonderful product of Math for testing"
validProducts[1].price = 1.99
validProducts[1].productIdentifier = "com.tinytapps.pandamath.full"
unpackValidProducts()
end
end
-------------------------------------------------------------------------------
-- Main
-------------------------------------------------------------------------------
-- Show title card
showTitle ()
-- Connect to store at startup
store.init (transactionCallback )
print ("After init")
-- Hide title card, run store
timer.performWithDelay (1000, setupMyStore)
end
end
I was testing the scope for Lua and noticed something unexpected. The following code does not print the localMainVariable.
function functionScope()
print( "\nIn function")
print( "globalMainVariable: " .. globalMainVariable )
if (localMainVariable ~= nil) then print( "localMainVariable: " .. localMainVariable ) end
end
globalMainVariable = "Visible"
local localMainVariable = "Visible"
functionScope()
But the following code does print localMainVariable.
globalMainVariable = "Visible"
local localMainVariable = "Visible"
function functionScope()
print( "\nIn function")
print( "globalMainVariable: " .. globalMainVariable )
if (localMainVariable ~= nil) then print( "localMainVariable: " .. localMainVariable ) end
end
functionScope()
I know it has something to do with where the localMainVariable was declared, but I thought making it local would limit the scope of the variable. What is the actual rule?
Thanks
The scope of a local variable begins at the first statement after its
declaration and lasts until the last non-void statement of the
innermost block that includes the declaration.
Lua manual
Very quick, and probably easy question... but its left me stumped for the last 30 minutes... But how can I remove items from the canvas/screen?
I know this works with removeSelf(), but I'm not quite sure how to use that in my example:
display.setStatusBar( display.HiddenStatusBar )
function cat1()
displayCategory(1)
print( "clicked 1" )
end
function cat2()
displayCategory(2)
print( "clicked 2" )
end
function cat3()
displayCategory(3)
print( "clicked 3" )
end
--category display
function displayCategory(cat)
if (cat == nil) then
cat = 1
end
print( cat )
if (cat == 1) then
local item1 = display.newRect(100,100,100,100)
item1:setFillColor(255,255,0)
elseif (cat == 2) then
local item2 = display.newRect(200,100,100,100)
item2:setFillColor(255,0,255)
elseif (cat == 3) then
local item3 = display.newRect(300,100,100,100)
item3:setFillColor(0,255,255)
end
end
--category buttons
local catBtn1 = display.newRect(0,0,50,50)
catBtn1:setFillColor( 255,0,0 )
catBtn1:addEventListener( "tap", cat1 )
local catBtn2 = display.newRect(60,0,50,50)
catBtn2:setFillColor( 0,255,0 )
catBtn2:addEventListener( "tap", cat2 )
local catBtn3 = display.newRect(120,0,50,50)
catBtn3:setFillColor( 0,0,255 )
catBtn3:addEventListener( "tap", cat3 )
Right now, every time I click on of my buttons, the corresponding item pops up, but doesnt disappear when I click on any of the other buttons. How would I go about that?
First, create those itens on start, before the displayCategory function.
Then you set them to not visible, like this:
local item1 = display.newRect(100,100,100,100)
item1:setFillColor(255,255,0)
item1.isVisible = false
Later you set the proper itens to visible or not as appropriate, in case of item 2 it would be
item1.isVisible = false
item2.isVisible = true
item3.isVisible = false