Skip to content

Instantly share code, notes, and snippets.

@y2bd y2bd/twitterer.lua
Last active May 19, 2016

What would you like to do?
Twitter URL generator for Lua
local tweet, map, appendparam, encode
local Twitterer = setmetatable({tweet=tweet}, {__call = function(t, params) return tweet(params) end})
tweet = function(params)
text = params[1] or params.text or nil
url = params[2] or params.url or nil
via = params[3] or params.via or nil
hashtags = params[4] or params.hashtags or nil
related = params[5] or params.related or nil
twiturl = ""
if text then
twiturl = appendparam(twiturl, "text", encode(text))
if url then
twiturl = appendparam(twiturl, "url", encode(url))
if via then
via = string.gsub(via, "@", "") -- don't need at signs
twiturl = appendparam(twiturl, "via", encode(via))
if hashtags then
if type(hashtags) ~= "table" then hashtags = { hashtags } end
hashtags = map(function(hashtag) return encode(string.gsub(hashtag, "#", "")) end, hashtags)
twiturl = appendparam(twiturl, "hashtags", table.concat(hashtags, ","))
if related then
if type(related[1]) ~= "table" then related = map(function(rel) return { rel } end, related) end
local function encoderelated(rel)
rel[1] = string.gsub(rel[1], "@", "")
if #rel > 1 then
return encode(rel[1] .. ":" .. rel[2])
return rel[1]
related = map(encoderelated, related)
twiturl = appendparam(twiturl, "related", table.concat(related, ","))
return twiturl
map = function(func, table)
local mapped = {}
for k,v in ipairs(table) do
mapped[#mapped+1] = func(v)
return mapped
appendparam = function(to, pname, pvalue)
return to .. pname .. "=" .. pvalue .. "&"
encode = function(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
return str
return Twitterer
-- how to use
local url = ""
-- just a basic tweet
url = Twitterer{text="Hello Twitter!"}
-- tweet a url, it'll be autoshortened if necessary
url = Twitterer{url=""}
-- via adds a " via @account" to the end the tweet
-- related lets you suggest twitter accounts for the user to follow,
-- some optional description text
url = Twitterer{text="Using this awesome Twitter URL generator!!",
related={{"@y2bd", "Developer of the library."}}}
-- autoappend hashtags to the end of your tweet
url = Twitterer{text="Getting ready for Ludum Dare!",
hashtags={"#ld48", "#ld30"}}
-- putting it all together
url = Twitterer{text="Quickly, get ready for Ludum Dare! I'm using Love2D!",
hashtags={"#ld48", "#gamejam"},
related={{"@ludumdare", "Official Ludum Dare Twitter Account"},
-- open with love2d
-- success is a bool that'll tell you if the url was opened successfully
success = love.system.openURL(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.