Skip to content

Instantly share code, notes, and snippets.

@jcbnlsn
Last active November 17, 2015 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcbnlsn/33c8ff847572be80f15a to your computer and use it in GitHub Desktop.
Save jcbnlsn/33c8ff847572be80f15a to your computer and use it in GitHub Desktop.
OSX Pasteboard
---------------------------------------------------------------------------------
-- Example
---------------------------------------------------------------------------------
local pb = require( "pasteboard" )
pb.copy("Hello osx pasteboard")
print ( pb.paste() )
pb.clear()
-- -------------------------------------------------------------------------------
-- pasteboard.lua - copy/paste string to pasteboard for Corona SDK Mac OSX builds
-- -------------------------------------------------------------------------------
local _M = {}
local lfs = require( "lfs" )
function _M.copy(s)
if type(s)=="string" then
os.execute( [[echo ']]..string.gsub(s, "'", "'\\''")..[[' | pbcopy]] )
end
end
function _M.paste()
local stamp = os.time(os.date('*t'))
local filename = "pb_"..stamp..".txt"
local current_dir = lfs.currentdir ()
lfs.chdir ( system.pathForFile( "", system.CachesDirectory ) )
os.execute( "pbpaste > "..filename )
local file, errorString, content = io.open( system.pathForFile( filename, system.CachesDirectory ), "r" )
if file then
content = file:read( "*a" )
io.close( file )
end
file = nil
os.remove( system.pathForFile( filename, system.CachesDirectory ) )
lfs.chdir ( current_dir )
return content
end
_M.clear = function() _M.copy('') end
return _M
@schroederapps
Copy link

This is AWESOME! But as written it can run into problems with strings that have single-quotes. If you change line 11 to this:

os.execute( [[echo "]]..string.gsub(s, '"', '\"')..[[" | pbcopy]] )

...then it has no problems with strings containing single-quotes, double-quotes, or any combination of the two, at least in my testing. But huge thanks for coming up with this very useful bit of code!

@jcbnlsn
Copy link
Author

jcbnlsn commented Oct 10, 2015

Thanks. I updated the code.

@fungusmungus
Copy link

This is really awesome! Very clever way to get copy/paste functionality into OS X builds in Corona SDK. I'm using this in a project that I will be releasing soon. One thing I didn't like was the CR/LF that got copied with my text. I fixed this by changing "echo" to "printf". That allowed me to copy and paste just the text I needed without the CR/LF.

@jcbnlsn
Copy link
Author

jcbnlsn commented Oct 15, 2015

Thanks. Nice to know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment