What program to use for lua
i found out about lua but idk where to start, i dont know which program to use and where to learn the lua programing language T_T
https://redd.it/1gpi7mb
@r_lua
i found out about lua but idk where to start, i dont know which program to use and where to learn the lua programing language T_T
https://redd.it/1gpi7mb
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
what is wrong with this code why doesn't it work? i started learning noscripting today and was trying functions
local baseplate = game.Workspace.Baseplate
local function changebaseplate()
baseplate.Material = "pebble"
end
changebaseplate()
https://redd.it/1gpont5
@r_lua
local baseplate = game.Workspace.Baseplate
local function changebaseplate()
baseplate.Material = "pebble"
end
changebaseplate()
https://redd.it/1gpont5
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
Rainmeter skin not working properly when I try to call a Lua function
The code (look at MeasureInPercent):
Rainmeter
Update=1000
Author=Connect-R
BackgroundMode=2
SolidColor=0,0,0,1
DynamicWindowSize=1
AccurateText=1
MouseScrollUpAction=!SetVariable Scale "(#Scale#+#ScrollMouseIncrement#)"!WriteKeyValue Variables Scale "(#Scale#+#ScrollMouseIncrement#)"!Refresh
MouseScrollDownAction=!SetVariable Scale "(#Scale#-#ScrollMouseIncrement# < 0.2 ? 0.2 : #Scale#-#ScrollMouseIncrement#)"!WriteKeyValue Variables Scale "(#Scale#-#ScrollMouseIncrement# < 0.2 ? 0.2 : #Scale#-#ScrollMouseIncrement#)"!Refresh
Variables
@include=#@#Variables.inc
@include2=#@#Language\#Language#.inc
Scale=0.87
;-------------------------------------------------------------
;-------------------------------------------------------------
MeasureTime
Measure=Time
Format="%#Format#:%M"
MeasureAMPM
Measure=Time
Format="%p"
MeasureTimeOfDay
Measure=Time
Format="%H"
Substitute=#TimeOfDay#
;-------------------------------------------------------------
;-------------------------------------------------------------
MeasureHours
Measure=Time
Format=%H
MeasureMinutes
Measure=Time
Format=%M
MeasureSeconds
Measure=Time
Format=%S
;-------------------------------------------------------------
;-------------------------------------------------------------
AdjustedTimeScript
Measure=Script
ScriptFile=#@#\LuaScript\AdjustedTime.lua
MeasureTotalSeconds
Measure=Calc
Formula=(MeasureHours3600)+(MeasureMinutes60)+(MeasureSeconds)
MeasureInPercent
Measure=String
Formula=&AdjustedTimeScript:CalculatePercentage([&MeasureHours, &MeasureMinutes, &MeasureSeconds)]
DynamicVariables=1
;-------------------------------------------------------------
;-------------------------------------------------------------
Meter24h
Meter=String
MeasureName=MeasureTime
MeasureName2=MeasureTimeOfDay
MeasureName3=MeasureInPercent
StringAlign=Center
FontColor=#Color4#
FontFace=Quicksand Regular
FontSize=(20#Scale#)
X=(600#Scale#)
Y=(0#Scale#)
Text="Time: %1, %2.#CRLF# Day Progress: %3% ."
AntiAlias=1
NumOfDecimals=0
Percentual=1
Hidden=#Hidden#
[Meter12h]
Meter=String
MeasureName=MeasureTime
MeasureName2=MeasureAMPM
MeasureName3=MeasureTimeOfDay
MeasureName4=MeasureInPercent
StringAlign=Center
FontColor=#Color4#
FontFace=Quicksand Regular
FontSize=(100#Scale#)
X=(600#Scale#)
Y=(0#Scale#)
Text="#Time:# %1 %2 #,# %3.#CRLF# Day Progress: %4% ."
AntiAlias=1
NumOfDecimals=0
Percentual=1
Hidden=#Hidden2#
The Lua Script:
function CalculatePercentage(hours, minutes, seconds)
if hours >= 4 and hours < 8 then
return "Time to Sleep."
elseif hours < 4 then
hours = hours + 16
end
local totalSeconds = (hours 3600) + (minutes 60) + seconds
abc = (totalSeconds / (86400 - 4 3600)) 100
return toString(abc)
end
I genuinely have no idea what I am doing wrong. Having an experience programming in Java, C, Python, Lua seems easy, but I really can't call it properly or make it return a value.
What should I do?
https://redd.it/1gqc2uu
@r_lua
The code (look at MeasureInPercent):
Rainmeter
Update=1000
Author=Connect-R
BackgroundMode=2
SolidColor=0,0,0,1
DynamicWindowSize=1
AccurateText=1
MouseScrollUpAction=!SetVariable Scale "(#Scale#+#ScrollMouseIncrement#)"!WriteKeyValue Variables Scale "(#Scale#+#ScrollMouseIncrement#)"!Refresh
MouseScrollDownAction=!SetVariable Scale "(#Scale#-#ScrollMouseIncrement# < 0.2 ? 0.2 : #Scale#-#ScrollMouseIncrement#)"!WriteKeyValue Variables Scale "(#Scale#-#ScrollMouseIncrement# < 0.2 ? 0.2 : #Scale#-#ScrollMouseIncrement#)"!Refresh
Variables
@include=#@#Variables.inc
@include2=#@#Language\#Language#.inc
Scale=0.87
;-------------------------------------------------------------
;-------------------------------------------------------------
MeasureTime
Measure=Time
Format="%#Format#:%M"
MeasureAMPM
Measure=Time
Format="%p"
MeasureTimeOfDay
Measure=Time
Format="%H"
Substitute=#TimeOfDay#
;-------------------------------------------------------------
;-------------------------------------------------------------
MeasureHours
Measure=Time
Format=%H
MeasureMinutes
Measure=Time
Format=%M
MeasureSeconds
Measure=Time
Format=%S
;-------------------------------------------------------------
;-------------------------------------------------------------
AdjustedTimeScript
Measure=Script
ScriptFile=#@#\LuaScript\AdjustedTime.lua
MeasureTotalSeconds
Measure=Calc
Formula=(MeasureHours3600)+(MeasureMinutes60)+(MeasureSeconds)
MeasureInPercent
Measure=String
Formula=&AdjustedTimeScript:CalculatePercentage([&MeasureHours, &MeasureMinutes, &MeasureSeconds)]
DynamicVariables=1
;-------------------------------------------------------------
;-------------------------------------------------------------
Meter24h
Meter=String
MeasureName=MeasureTime
MeasureName2=MeasureTimeOfDay
MeasureName3=MeasureInPercent
StringAlign=Center
FontColor=#Color4#
FontFace=Quicksand Regular
FontSize=(20#Scale#)
X=(600#Scale#)
Y=(0#Scale#)
Text="Time: %1, %2.#CRLF# Day Progress: %3% ."
AntiAlias=1
NumOfDecimals=0
Percentual=1
Hidden=#Hidden#
[Meter12h]
Meter=String
MeasureName=MeasureTime
MeasureName2=MeasureAMPM
MeasureName3=MeasureTimeOfDay
MeasureName4=MeasureInPercent
StringAlign=Center
FontColor=#Color4#
FontFace=Quicksand Regular
FontSize=(100#Scale#)
X=(600#Scale#)
Y=(0#Scale#)
Text="#Time:# %1 %2 #,# %3.#CRLF# Day Progress: %4% ."
AntiAlias=1
NumOfDecimals=0
Percentual=1
Hidden=#Hidden2#
The Lua Script:
function CalculatePercentage(hours, minutes, seconds)
if hours >= 4 and hours < 8 then
return "Time to Sleep."
elseif hours < 4 then
hours = hours + 16
end
local totalSeconds = (hours 3600) + (minutes 60) + seconds
abc = (totalSeconds / (86400 - 4 3600)) 100
return toString(abc)
end
I genuinely have no idea what I am doing wrong. Having an experience programming in Java, C, Python, Lua seems easy, but I really can't call it properly or make it return a value.
What should I do?
https://redd.it/1gqc2uu
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
LuaLS annotation: class' cannot have multiple values; {Metric,module}
Hello everyone.
I am writing some internal lua modules, I am trying to annotate it correctly (using LLS standard) as there are various classes and modules but I keep having an error of this type :
ldoc --lls -a -d docs/lua/src/
lua/src/prometheus/metric.lua:14: ?: 'class' cannot have multiple values; {Metric,module}
My IDE (Pycharm) is happy with it however and resolves everything without any issue (with annotation based autocompletion)
In this prometheus/ folder, I have my init.lua file that has the following annotation on top
--- @module prometheus
local prometheus = {}
require("prometheus.metric")
...
In the same folder, I have the metric.lua file that contains the following one
--- A Metric
--- @class Metric
--- @field name string the name of the metric
--- @field value number the value of the metric
--- @field labels table the labels of the metric
Metric = {}
...
I don't understand how there conflict as they are on different files ? I found other example of lua project doing this even on the same file and not having any kind of conflicts.
I have no idea what I am doing wrong ?
Thanks
https://redd.it/1grtkb3
@r_lua
Hello everyone.
I am writing some internal lua modules, I am trying to annotate it correctly (using LLS standard) as there are various classes and modules but I keep having an error of this type :
ldoc --lls -a -d docs/lua/src/
lua/src/prometheus/metric.lua:14: ?: 'class' cannot have multiple values; {Metric,module}
My IDE (Pycharm) is happy with it however and resolves everything without any issue (with annotation based autocompletion)
In this prometheus/ folder, I have my init.lua file that has the following annotation on top
--- @module prometheus
local prometheus = {}
require("prometheus.metric")
...
In the same folder, I have the metric.lua file that contains the following one
--- A Metric
--- @class Metric
--- @field name string the name of the metric
--- @field value number the value of the metric
--- @field labels table the labels of the metric
Metric = {}
...
I don't understand how there conflict as they are on different files ? I found other example of lua project doing this even on the same file and not having any kind of conflicts.
I have no idea what I am doing wrong ?
Thanks
https://redd.it/1grtkb3
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
How do you run busted multiple times, from Lua?
This is a cross-post from an existing GitHub discussion but I wanted to ask here since the other place seemed unlikely to get a reply.
The summary is that from what I can tell, busted cannot be reasonably called from Lua, let alone more than once. And I'm in a situation where I want to run busted several times and certain things with its results. How can I do it?
I'd like to use busted to profile unittests. But variation can cause tests to perform differently across runs (for example a cold cache vs a warm cache).
What I'd like to do is be able to run busted in a while loop that goes something like this
local maximumtries = 10
local counter = 10
local fastesttime = 2^1023
while true do
local before = os.clock()
runbustedsuite() -- The lua equivalent of this terminal call
local duration = os.clock() - before
if duration < fastesttime then
counter = maximumtries
fastesttime = duration
else
counter = counter - 1
end
if counter == 0 then
break
end
end
In the above example, a run that is the fastest of 10 consecutive runs is considered "probably the best time we're going to get". And then I'd use the profile results of that fastest run.
How can I achieve that easily with busted? I checked around it seems like busted isn't like other testing frameworks where you can call the test suite runner directly with lua.
I tried a real example using this:
local function cleararg()
for key, in pairs(arg) do
if key ~= 0 then
argkey = nil
end
end
end
local function keeparg(caller)
local original = vim.deepcopy(arg)
caller()
for key, value in pairs(original) do
argkey = value
end
end
local function runbustedsuite(runner)
keeparg(function()
cleararg()
arg[1] = "--ignore-lua"
arg[2] = "--helper=spec/minimalinit.lua"
arg3 = "--output=busted.profileusingflamegraph"
runner({ standalone=false })
end)
end
local function main()
local maximumtries = 10
local counter = 10
local fastesttime = 2^1023
while true do
print("running")
local before = os.clock()
local runner = require("busted.runner")
runbustedsuite(runner)
-- NOTE: It looks like for some reason busted forces `runner()` to
-- return an empty table if it is called more than once. Which is
-- weird. So we have to force-remove the module so we can load it from
-- scratch again.
--
package.loaded["busted.runner"] = nil
local duration = os.clock() - before
if duration < fastesttime then
counter = maximumtries
fastesttime = duration
else
counter = counter - 1
end
if counter == 0 then
break
end
end
end
main()
Because runner takes a combination of
I've tried a second pass at this where I basically copy the contents of busted.execute and try to do things that way. And that's difficult in entirely separate ways.
Anyway I'm struggling to
This is a cross-post from an existing GitHub discussion but I wanted to ask here since the other place seemed unlikely to get a reply.
The summary is that from what I can tell, busted cannot be reasonably called from Lua, let alone more than once. And I'm in a situation where I want to run busted several times and certain things with its results. How can I do it?
I'd like to use busted to profile unittests. But variation can cause tests to perform differently across runs (for example a cold cache vs a warm cache).
What I'd like to do is be able to run busted in a while loop that goes something like this
local maximumtries = 10
local counter = 10
local fastesttime = 2^1023
while true do
local before = os.clock()
runbustedsuite() -- The lua equivalent of this terminal call
busted --helper spec/minimal_init.lua --output=my_cool_profiler .local duration = os.clock() - before
if duration < fastesttime then
counter = maximumtries
fastesttime = duration
else
counter = counter - 1
end
if counter == 0 then
break
end
end
In the above example, a run that is the fastest of 10 consecutive runs is considered "probably the best time we're going to get". And then I'd use the profile results of that fastest run.
How can I achieve that easily with busted? I checked around it seems like busted isn't like other testing frameworks where you can call the test suite runner directly with lua.
I tried a real example using this:
local function cleararg()
for key, in pairs(arg) do
if key ~= 0 then
argkey = nil
end
end
end
local function keeparg(caller)
local original = vim.deepcopy(arg)
caller()
for key, value in pairs(original) do
argkey = value
end
end
local function runbustedsuite(runner)
keeparg(function()
cleararg()
arg[1] = "--ignore-lua"
arg[2] = "--helper=spec/minimalinit.lua"
arg3 = "--output=busted.profileusingflamegraph"
runner({ standalone=false })
end)
end
local function main()
local maximumtries = 10
local counter = 10
local fastesttime = 2^1023
while true do
print("running")
local before = os.clock()
local runner = require("busted.runner")
runbustedsuite(runner)
-- NOTE: It looks like for some reason busted forces `runner()` to
-- return an empty table if it is called more than once. Which is
-- weird. So we have to force-remove the module so we can load it from
-- scratch again.
--
package.loaded["busted.runner"] = nil
local duration = os.clock() - before
if duration < fastesttime then
counter = maximumtries
fastesttime = duration
else
counter = counter - 1
end
if counter == 0 then
break
end
end
end
main()
Because runner takes a combination of
arg and options, the interface for this gets hacky. And then there's this if loaded then return function() end else loaded = true end that prevents me from calling the runner more than once. I tried to get around it by forcing the file to reload with package.loaded["busted.runner"] = nil but it isn't working just yet.I've tried a second pass at this where I basically copy the contents of busted.execute and try to do things that way. And that's difficult in entirely separate ways.
Anyway I'm struggling to
GitHub
How can I run busted tests in a while loop until a fastest time is found? · lunarmodules/busted · Discussion #746
I'd like to use busted to profile unittests. But variation can cause tests to perform differently across runs (for example a cold cache vs a warm cache). What I'd like to do is be able to r...
achieve the effect I'm looking for. Any advice would be appreciated. Maybe I'm just looking in the wrong place and there's an easy way to do this?
https://redd.it/1gsifv5
@r_lua
https://redd.it/1gsifv5
@r_lua
Reddit
From the lua community on Reddit: How do you run busted multiple times, from Lua?
Explore this post and more from the lua community
how can i check, if at least 2 of 3 given bools are true?
Hello i have 3 bools (to check, if a coordinate is along the edges of a cube with the given size of 16 units):
how must i setup the if-line to check, if at least 2 of these bool-lines are true?
https://redd.it/1gslmef
@r_lua
Hello i have 3 bools (to check, if a coordinate is along the edges of a cube with the given size of 16 units):
local bool_1 = x == 1 or x = 16 local bool_2 = y == 1 or y = 16 local bool_3 = z == 1 or z = 16how must i setup the if-line to check, if at least 2 of these bool-lines are true?
https://redd.it/1gslmef
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
Best app to learn LUA coding?
I'm currently searching for a safe app where to learn code.
https://redd.it/1gtlle7
@r_lua
I'm currently searching for a safe app where to learn code.
https://redd.it/1gtlle7
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
Is it possible to interpolate C/C++ code in Lua ?
So Recently I decided to check out Lua and it's Love2D Framework, I wanted to ask if anyone knows about how you can use C++ Code in Lua. I am aware that you can embed Lua code in cpp but can you do the opposite.
Any kind of Help will be Greatly Appreciated !
https://redd.it/1gu4nhz
@r_lua
So Recently I decided to check out Lua and it's Love2D Framework, I wanted to ask if anyone knows about how you can use C++ Code in Lua. I am aware that you can embed Lua code in cpp but can you do the opposite.
Any kind of Help will be Greatly Appreciated !
https://redd.it/1gu4nhz
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
Advice to learn Roblox-Lua?
Hi, i'm an aspiring developer on the Roblox platform. Recently I've started learning the fundamentals of Lua and I think I'm ready to take another step into Lua programming, it's fun! Which is why, I'm here asking for any tips or advice you have in for me to pursue this knowledge. Maybe there's a place to learn? Sort of like a website? Idk but I'd like to learn a lot more, that's for sure! Thank you in advance 🙏🙏
https://redd.it/1gueqvj
@r_lua
Hi, i'm an aspiring developer on the Roblox platform. Recently I've started learning the fundamentals of Lua and I think I'm ready to take another step into Lua programming, it's fun! Which is why, I'm here asking for any tips or advice you have in for me to pursue this knowledge. Maybe there's a place to learn? Sort of like a website? Idk but I'd like to learn a lot more, that's for sure! Thank you in advance 🙏🙏
https://redd.it/1gueqvj
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
Mudança de cor em Lua
Fala pessoal, gostaria de saber se existe alguma lib ou alguma forma, função, para manipulação de cores nos textos (para aplicações não gráficas do lado do usuário/terminal) em Lua ? ainda não achei nada com relação á isso.
https://redd.it/1gv9i9r
@r_lua
Fala pessoal, gostaria de saber se existe alguma lib ou alguma forma, função, para manipulação de cores nos textos (para aplicações não gráficas do lado do usuário/terminal) em Lua ? ainda não achei nada com relação á isso.
https://redd.it/1gv9i9r
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
Starting to code, beginning with LUA
Hey there! I decided that i wanna start to code, i'm new into this world and i need some tips and advices for beginners. My discord is n0etix.
I got a few experienced coders telling me to start with CS50x lectures to begin with, because without the basics, there's no code. Just like in math, without 2 plus 2 there's no pythagorean theorem..
Add me on discord, maybe we can discuss something together :)
https://redd.it/1gvl0zf
@r_lua
Hey there! I decided that i wanna start to code, i'm new into this world and i need some tips and advices for beginners. My discord is n0etix.
I got a few experienced coders telling me to start with CS50x lectures to begin with, because without the basics, there's no code. Just like in math, without 2 plus 2 there's no pythagorean theorem..
Add me on discord, maybe we can discuss something together :)
https://redd.it/1gvl0zf
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
How do i make a cfg system in lua?
So i wrote a noscript with dropdown boxes checkmarks and sliders but now what?
I want to make it read and write cfg files or txt or anything that can take the values and turn them into something that can be saved and loaded
https://redd.it/1gws7cw
@r_lua
So i wrote a noscript with dropdown boxes checkmarks and sliders but now what?
I want to make it read and write cfg files or txt or anything that can take the values and turn them into something that can be saved and loaded
https://redd.it/1gws7cw
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
Tips to make this less cursed?
I have this function that's supposed to get options from a config table. I wanted to make it possible to have any of the keys be functions and still work like a simple nested table.
So, I made this,
This works, but also looks very cursed. Any tips to improve the code?
https://redd.it/1gwxjq2
@r_lua
I have this function that's supposed to get options from a config table. I wanted to make it possible to have any of the keys be functions and still work like a simple nested table.
So, I made this,
local __get = function (keys, opts)
if not opts then opts = {}; end
local meta;
local __proxy = {};
local _c = {
vi = {
enable = function ()
return {
test = 10
};
end
},
_f = function ()
return "hi"
end
};
meta = {
__index = function (_, key)
local _v = rawget(_c, key);
---@diagnostic disable
if
(
not opts.return_raw or
(
opts.return_raw and
opts.return_raw[key] ~= false
)
) and
pcall(_v, unpack(opts.args or {}))
then
return _v(unpack(opts.args or {}));
---@diagnostic enable
elseif type(_v) == "table" then
setmetatable(_v, meta)
end
return _v;
end
};
setmetatable(__proxy, meta);
for _, key in ipairs(keys) do
if
type(__proxy[key]) == "table" and
__proxy[key].enable ~= false
then
_c = __proxy[key];
setmetatable(__proxy, meta);
elseif __proxy[key] then
_c = _c[key];
setmetatable(__proxy, meta);
else
return opts.fallback;
end
end
---@diagnostic disable
if pcall(_c, unpack(opts.args or {})) then
return _c(unpack(opts.args or {}));
end
---@diagnostic enable
return _c;
end
print(
__get({"vi", "enable", "test"})
)
This works, but also looks very cursed. Any tips to improve the code?
https://redd.it/1gwxjq2
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
Is there a way to put every part of a lua in 1 line after coding it?
I made a lua (about 4600 lines of code) and i want to put it in 1 line so people can’t steal the code as easily, how can i do that?
https://redd.it/1gx4892
@r_lua
I made a lua (about 4600 lines of code) and i want to put it in 1 line so people can’t steal the code as easily, how can i do that?
https://redd.it/1gx4892
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
Working with WebRTC from fengari lua in the browser...first steps
I decided to create this simple RTCDataChannel example in lua using fengari. The most interesting part of this process was figuring out how to translate the promise-chaining as seen here:
localConnection.createOffer()
.then(offer => localConnection.setLocalDenoscription(offer))
.then(() => remoteConnection.setRemoteDenoscription(localConnection.localDenoscription))
.then(() => remoteConnection.createAnswer())
.then(answer => remoteConnection.setLocalDenoscription(answer))
.then(() => localConnection.setRemoteDenoscription(remoteConnection.localDenoscription))
.catch(handleCreateDenoscriptionError);
I had to create the then, catch, finally functions in addition to the pdo function which starts the chain.
weft.fengari:
js=require('js')
window=js.global
document=window.document
function then(prom,...)
local p=prom['then'](prom,...)
if p then
p.then = then
p.catch = catch
p.finally = finally
end
return p
end
function catch(prom,...)
local p=prom'catch'
if p then
p.then = then
p.catch = catch
p.finally = finally
end
return p
end
function finally(prom,...)
local p=prom['finally'](prom,...)
if p then
p.then = then
p.catch = catch
p.finally = finally
end
return p
end
function pdo(p)
p.then=then
p.catch=catch
p.finally=finally
return p
end
function elevate(from,members)
-- "elevates" table of top level members of a js object (from) into global, for convenience
for , v in ipairs(members) do
ENVv=fromv
end
end
elevate(js.global,{
'console',
'RTCPeerConnection'
})
local connectButton = nil
local disconnectButton = nil
local sendButton = nil
local messageInputBox = nil
local receiveBox = nil
local localConnection = nil -- RTCPeerConnection for our "local" connection
local remoteConnection = nil -- RTCPeerConnection for the "remote"
local sendChannel = nil -- RTCDataChannel for the local (sender)
local receiveChannel = nil -- RTCDataChannel for the remote (receiver)
function handleCreateDenoscriptionError(error)
console:log('unable to create an offer')
end
function handleLocalAddCandidateSuccess()
connectButton.disabled = true
end
function handleRemoteAddCandidateSuccess()
disconnectButton.disabled = false
end
function handleAddCandidateError()
console:log("Oh noes! addICECandidate failed!")
end
-- Handles clicks on the "Send" button by transmitting
-- a message to the remote peer.
function sendMessage()
local message = messageInputBox.value
sendChannel:send(message)
-- Clear the input box and re-focus it, so that we are
-- ready for the next message.
messageInputBox.value = ""
messageInputBox:focus()
end
-- Handle status changes on the local end of the data
-- channel; this is the end doing the sending of data
-- in this example.
function handleSendChannelStatusChange(self,event)
if (sendChannel) then
local state = sendChannel.readyState
console:log('sendChannel',state)
if (state == "open") then
messageInputBox.disabled = false
messageInputBox:focus()
sendButton.disabled = false
disconnectButton.disabled = false
connectButton.disabled = true
else
messageInputBox.disabled = true
sendButton.disabled = true
connectButton.disabled = false
disconnectButton.disabled = true
end
end
end
-- Called when the connection opens and the data
-- channel is ready to be connected to the remote.
function
I decided to create this simple RTCDataChannel example in lua using fengari. The most interesting part of this process was figuring out how to translate the promise-chaining as seen here:
localConnection.createOffer()
.then(offer => localConnection.setLocalDenoscription(offer))
.then(() => remoteConnection.setRemoteDenoscription(localConnection.localDenoscription))
.then(() => remoteConnection.createAnswer())
.then(answer => remoteConnection.setLocalDenoscription(answer))
.then(() => localConnection.setRemoteDenoscription(remoteConnection.localDenoscription))
.catch(handleCreateDenoscriptionError);
I had to create the then, catch, finally functions in addition to the pdo function which starts the chain.
weft.fengari:
js=require('js')
window=js.global
document=window.document
function then(prom,...)
local p=prom['then'](prom,...)
if p then
p.then = then
p.catch = catch
p.finally = finally
end
return p
end
function catch(prom,...)
local p=prom'catch'
if p then
p.then = then
p.catch = catch
p.finally = finally
end
return p
end
function finally(prom,...)
local p=prom['finally'](prom,...)
if p then
p.then = then
p.catch = catch
p.finally = finally
end
return p
end
function pdo(p)
p.then=then
p.catch=catch
p.finally=finally
return p
end
function elevate(from,members)
-- "elevates" table of top level members of a js object (from) into global, for convenience
for , v in ipairs(members) do
ENVv=fromv
end
end
elevate(js.global,{
'console',
'RTCPeerConnection'
})
local connectButton = nil
local disconnectButton = nil
local sendButton = nil
local messageInputBox = nil
local receiveBox = nil
local localConnection = nil -- RTCPeerConnection for our "local" connection
local remoteConnection = nil -- RTCPeerConnection for the "remote"
local sendChannel = nil -- RTCDataChannel for the local (sender)
local receiveChannel = nil -- RTCDataChannel for the remote (receiver)
function handleCreateDenoscriptionError(error)
console:log('unable to create an offer')
end
function handleLocalAddCandidateSuccess()
connectButton.disabled = true
end
function handleRemoteAddCandidateSuccess()
disconnectButton.disabled = false
end
function handleAddCandidateError()
console:log("Oh noes! addICECandidate failed!")
end
-- Handles clicks on the "Send" button by transmitting
-- a message to the remote peer.
function sendMessage()
local message = messageInputBox.value
sendChannel:send(message)
-- Clear the input box and re-focus it, so that we are
-- ready for the next message.
messageInputBox.value = ""
messageInputBox:focus()
end
-- Handle status changes on the local end of the data
-- channel; this is the end doing the sending of data
-- in this example.
function handleSendChannelStatusChange(self,event)
if (sendChannel) then
local state = sendChannel.readyState
console:log('sendChannel',state)
if (state == "open") then
messageInputBox.disabled = false
messageInputBox:focus()
sendButton.disabled = false
disconnectButton.disabled = false
connectButton.disabled = true
else
messageInputBox.disabled = true
sendButton.disabled = true
connectButton.disabled = false
disconnectButton.disabled = true
end
end
end
-- Called when the connection opens and the data
-- channel is ready to be connected to the remote.
function
MDN Web Docs
A simple RTCDataChannel sample - Web APIs | MDN
The RTCDataChannel interface is a feature of the WebRTC API which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the WebSocket API, so that the same programming model can be…