The community forums are in BETA and closed to the public.

Quick Start Guide using Lua SDK on PubNub

Quick Start Guide using Lua SDK on PubNub

This is a quick guide with copy/paste code snippets which allow you to use the basic features of PubNub with our Lua SDK.

Initialize PubNub Connection

require "pubnub" 

-- 
-- GET YOUR PUBNUB KEYS HERE: 
-- http://www.pubnub.com/account#api-keys 
-- 
connection = pubnub.new({ 
    publish_key   = "demo",             -- YOUR PUBLISH KEY 
    subscribe_key = "demo",             -- YOUR SUBSCRIBE KEY 
    secret_key    = nil,                -- YOUR SECRET KEY 
    ssl           = nil                 -- ENABLE SSL?
})

Subscribe to a Data Stream Channel

-- 
-- PUBNUB SUBSCRIBE CHANNEL (RECEIVE MESSAGES) 
-- 
connection:subscribe({ 
    channel  = "lua-channel",
    callback = function(message) 
        -- MESSAGE RECEIVED!!! 
        print(message) 
    end,
    errorback = function() 
        print("Network Connection Lost") 
    end 
})

Publish a JSON Lua Table/Array

-- 
-- PUBNUB PUBLISH MESSAGE (SEND A MESSAGE) 
-- 
connection:publish({ 
    channel  = "lua-channel",
    message  = { "1234", 2, 3, 4 },
    callback = function(info) 

        -- WAS MESSAGE DELIVERED? 
        if info[1] then 
            print("MESSAGE DELIVERED SUCCESSFULLY!") 
        else 
            print("MESSAGE FAILED BECAUSE -> " .. info[2]) 
        end 

    end 
})

Unsubscribe from a PubNub Data Stream Channel

-- 
-- PUBNUB UN-SUBSCRIBE CHANNEL (STOP RECEIVING MESSAGES) 
-- 
connection:unsubscribe({ 
    channel = "lua-channel" 
})

Fetch Historical JSON Lua Table/Array Messages on a Data Stream Channel

-- 
-- PUBNUB LOAD MESSAGE HISTORY 
-- 
connection:history({ 
    channel  = "lua-corona-demo-channel",
    limit    = 10,
    callback = function(messages) 
        if not messages then 
            return print("ERROR LOADING HISTORY") 
        end 

        -- NO HISTORY? 
        if not (#messages > 0) then 
            return print("NO HISTORY YET") 
        end 

        -- LOOP THROUGH MESSAGE HISTORY 
        for i, message in ipairs(messages) do 
            print(Json.Encode(message)) 
        end 
    end 
})

Comments to this discussion are now closed!