Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a functionally identical Lua code for the snippet given in VB. | Module Module1
Sub Print(ls As List(Of Integer))
Dim iter = ls.GetEnumerator
Console.Write("[")
If iter.MoveNext Then
Console.Write(iter.Current)
End If
While iter.MoveNext
Console.Write(", ")
Console.Write(iter.Current)
End While
... | local N = 2
local base = 10
local c1 = 0
local c2 = 0
for k = 1, math.pow(base, N) - 1 do
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
io.write(k .. ' ')
end
end
print()
print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 100.... |
Produce a language-to-language conversion: from VB to Lua, same semantics. | Public Sub Main()
Print "The tau functions for the first 100 positive integers are:\n"
For i As Integer = 1 To 100
Print Format$(numdiv(i), "####");
If i Mod 10 = 0 Then Print
Next
End
Public Function numdiv(n As Integer) As Integer
Dim c As Integer = 1
For i As Integer = 1 To (n + 1... | function divisorCount(n)
local total = 1
while (n & 1) == 0 do
total = total + 1
n = math.floor(n / 2)
end
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = n / p
end
total = tot... |
Generate an equivalent Lua version of this VB code. | Public Sub Main()
Print "The tau functions for the first 100 positive integers are:\n"
For i As Integer = 1 To 100
Print Format$(numdiv(i), "####");
If i Mod 10 = 0 Then Print
Next
End
Public Function numdiv(n As Integer) As Integer
Dim c As Integer = 1
For i As Integer = 1 To (n + 1... | function divisorCount(n)
local total = 1
while (n & 1) == 0 do
total = total + 1
n = math.floor(n / 2)
end
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = n / p
end
total = tot... |
Generate a Lua translation of this VB snippet without changing its computational steps. |
Function BFInpt(s, sp, d, dp, i, ip, o)
While sp < Len(s)
Select Case Mid(s, sp + 1, 1)
Case "+"
newd = Asc(d(dp)) + 1
If newd > 255 Then newd = newd Mod 256
d(dp) = Chr(newd)
Case "-"
newd = Asc(d(dp)) - 1
... | local funs = {
['>'] = 'ptr = ptr + 1; ',
['<'] = 'ptr = ptr - 1; ',
['+'] = 'mem[ptr] = mem[ptr] + 1; ',
['-'] = 'mem[ptr] = mem[ptr] - 1; ',
['['] = 'while mem[ptr] ~= 0 do ',
[']'] = 'end; ',
['.'] = 'io.write(string.char(mem[ptr])); ',
[','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ',
}
local prog = [[
local ... |
Maintain the same structure and functionality when rewriting this code in Lua. |
Function BFInpt(s, sp, d, dp, i, ip, o)
While sp < Len(s)
Select Case Mid(s, sp + 1, 1)
Case "+"
newd = Asc(d(dp)) + 1
If newd > 255 Then newd = newd Mod 256
d(dp) = Chr(newd)
Case "-"
newd = Asc(d(dp)) - 1
... | local funs = {
['>'] = 'ptr = ptr + 1; ',
['<'] = 'ptr = ptr - 1; ',
['+'] = 'mem[ptr] = mem[ptr] + 1; ',
['-'] = 'mem[ptr] = mem[ptr] - 1; ',
['['] = 'while mem[ptr] ~= 0 do ',
[']'] = 'end; ',
['.'] = 'io.write(string.char(mem[ptr])); ',
[','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ',
}
local prog = [[
local ... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | suite$ = "CDHS" #Club, Diamond, Heart, Spade
card$ = "A23456789TJQK" #Cards Ace to King
card = 0
dim n(55) #make ordered deck
for i = 1 to 52 # of 52 cards
n[i] = i
next i
for i = 1 to 52 * 3 #shuffle deck 3 times
i1 = int(rand * 5... | suits = {"Clubs", "Diamonds", "Hearts", "Spades"}
faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"}
stack = setmetatable({
__unm = function(z)
local ret = {}
for i = #z, 1, -1 do
ret[#ret + 1] = table.remove(z,math.random(i))
end
return setmetatable(ret, stack)
end,
__add = function(z, z2)
for ... |
Ensure the translated Lua code behaves exactly like the original VB snippet. | Option Explicit
Function two_sum(a As Variant, t As Integer) As Variant
Dim i, j As Integer
i = 0
j = UBound(a)
Do While (i < j)
If (a(i) + a(j) = t) Then
two_sum = Array(i, j)
Exit Function
ElseIf (a(i) + a(j) < t) Then i = i + 1
ElseIf (a(i) + a(j) > t) ... | function twoSum (numbers, sum)
local i, j, s = 1, #numbers
while i < j do
s = numbers[i] + numbers[j]
if s == sum then
return {i, j}
elseif s < sum then
i = i + 1
else
j = j - 1
end
end
return {}
end
print(table.concat(twoSum({... |
Generate an equivalent Lua version of this VB code. | Option Explicit
Function two_sum(a As Variant, t As Integer) As Variant
Dim i, j As Integer
i = 0
j = UBound(a)
Do While (i < j)
If (a(i) + a(j) = t) Then
two_sum = Array(i, j)
Exit Function
ElseIf (a(i) + a(j) < t) Then i = i + 1
ElseIf (a(i) + a(j) > t) ... | function twoSum (numbers, sum)
local i, j, s = 1, #numbers
while i < j do
s = numbers[i] + numbers[j]
if s == sum then
return {i, j}
elseif s < sum then
i = i + 1
else
j = j - 1
end
end
return {}
end
print(table.concat(twoSum({... |
Write the same algorithm in Lua as shown in this VB implementation. | print "The first 100 tau numbers are:"
n = 0
num = 0
limit = 100
while num < limit
n = n +1
tau = 0
for m = 1 to n
if n mod m = 0 then tau = tau +1
next m
if n mod tau = 0 then
num = num +1
if num mod 10 = 1 then print
print using("######", n);
end if
wend
end
| function divisor_count(n)
local total = 1
while (n & 1) == 0 do
total = total + 1
n = n >> 1
end
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = math.floor(n / p)
end
total = ... |
Generate an equivalent Lua version of this VB code. | Imports System
Imports System.Console
Imports LI = System.Collections.Generic.SortedSet(Of Integer)
Module Module1
Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI
If lft = 0 Then
res.Add(vlu)
... | function prime_digits_sum_13(n)
local sum = 0
while n > 0 do
local r = n % 10
if r ~= 2 and r ~= 3 and r ~= 5 and r ~= 7 then
return false
end
n = math.floor(n / 10)
sum = sum + r
end
return sum == 13
end
local c = 0
for i=1,999999 do
if prime_dig... |
Translate the given VB code snippet into Lua without altering its behavior. | Imports System
Imports System.Console
Imports LI = System.Collections.Generic.SortedSet(Of Integer)
Module Module1
Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI
If lft = 0 Then
res.Add(vlu)
... | function prime_digits_sum_13(n)
local sum = 0
while n > 0 do
local r = n % 10
if r ~= 2 and r ~= 3 and r ~= 5 and r ~= 7 then
return false
end
n = math.floor(n / 10)
sum = sum + r
end
return sum == 13
end
local c = 0
for i=1,999999 do
if prime_dig... |
Change the programming language of this snippet from VB to Lua without modifying what it does. | Imports System
Imports System.Numerics
Imports Microsoft.VisualBasic.Strings
Public Module Module1
Public Function IntSqRoot(v As BigInteger) As BigInteger
Dim digs As Integer = Math.Max(0, v.ToString().Length / 2 - 1)
IntSqRoot = BigInteger.Parse("3" & StrDup(digs, "0"))
Dim term As BigIn... | function root(base, n)
if base < 2 then return base end
if n == 0 then return 1 end
local n1 = n - 1
local n2 = n
local n3 = n1
local c = 1
local d = math.floor((n3 + base) / n2)
local e = math.floor((n3 * d + base / math.pow(d, n1)) / n2)
while c ~= d and c ~= e do
c = d
... |
Produce a language-to-language conversion: from VB to Lua, same semantics. | Imports System
Imports System.Numerics
Imports Microsoft.VisualBasic.Strings
Public Module Module1
Public Function IntSqRoot(v As BigInteger) As BigInteger
Dim digs As Integer = Math.Max(0, v.ToString().Length / 2 - 1)
IntSqRoot = BigInteger.Parse("3" & StrDup(digs, "0"))
Dim term As BigIn... | function root(base, n)
if base < 2 then return base end
if n == 0 then return 1 end
local n1 = n - 1
local n2 = n
local n3 = n1
local c = 1
local d = math.floor((n3 + base) / n2)
local e = math.floor((n3 * d + base / math.pow(d, n1)) / n2)
while c ~= d and c ~= e do
c = d
... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | Module Module1
Function Turn(base As Integer, n As Integer) As Integer
Dim sum = 0
While n <> 0
Dim re = n Mod base
n \= base
sum += re
End While
Return sum Mod base
End Function
Sub Fairshare(base As Integer, count As Integer)
Co... | function turn(base, n)
local sum = 0
while n ~= 0 do
local re = n % base
n = math.floor(n / base)
sum = sum + re
end
return sum % base
end
function fairShare(base, count)
io.write(string.format("Base %2d:", base))
for i=1,count do
local t = turn(base, i - 1)
... |
Translate the given VB code snippet into Lua without altering its behavior. | Imports System.Runtime.CompilerServices
Imports System.Text
Module Module1
Class Crutch
Public ReadOnly len As Integer
Public s() As Integer
Public i As Integer
Public Sub New(len As Integer)
Me.len = len
s = New Integer(len - 1) {}
i = 0
... | function next_in_cycle(c,length,index)
local pos = index % length
return c[pos]
end
function kolakoski(c,s,clen,slen)
local i = 0
local k = 0
while true do
s[i] = next_in_cycle(c,clen,k)
if s[k] > 1 then
for j=1,s[k]-1 do
i = i + 1
if i =... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | Sub Lis(arr() As Integer)
Dim As Integer lb = Lbound(arr), ub = Ubound(arr)
Dim As Integer i, lo, hi, mitad, newl, l = 0
Dim As Integer p(ub), m(ub)
For i = lb To ub
lo = 1
hi = l
Do While lo <= hi
mitad = Int((lo+hi)/2)
If arr(m(mitad)) < arr(i) Then
lo = mitad + 1
Else
h... | function buildLIS(seq)
local piles = { { {table.remove(seq, 1), nil} } }
while #seq>0 do
local x=table.remove(seq, 1)
for j=1,#piles do
if piles[j][#piles[j]][1]>x then
table.insert(piles[j], {x, (piles[j-1] and #piles[j-1])})
break
elseif ... |
Convert this VB snippet to Lua and keep its semantics consistent. | with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
set d=createobject("scripting.dictionary")
redim b(ubound(a))
i=0
for each x in a
s=trim(x)
if len(s)>=9 then
if len(s)= 9 then d.add s,""
b(i)=s
i=i+1
end if
nex... | wordlist, wordhash = {}, {}
for word in io.open("unixdict.txt", "r"):lines() do
if #word >= 9 then
wordlist[#wordlist+1] = word
wordhash[word] = #wordlist
end
end
for n = 1, #wordlist-8 do
local word = ""
for i = 0, 8 do
word = word .. wordlist[n+i]:sub(i+1,i+1)
end
if wordhash[word] then
... |
Ensure the translated Lua code behaves exactly like the original VB snippet. | Public Sub Main()
Dim h As Float = 0
Dim n As Integer, i As Integer
Print "The first twenty harmonic numbers are:"
For n = 1 To 20
h += 1 / n
Print n, h
Next
Print
h = 1
n = 2
For i = 2 To 10
While h < i
h += 1 / n
n += 1
Wend
Print "The first harm... |
function harmonic (n)
if n < 1 or n ~= math.floor(n) then
error("Argument to harmonic function is not a natural number")
end
local Hn = 1
for i = 2, n do
Hn = Hn + (1/i)
end
return Hn
end
for x = 1, 20 do
print(x .. " :\t" .. harmonic(x))
end
local x, lastInt, Hx = 0, 1
... |
Port the provided VB code into Lua while preserving the original functionality. | #macro assign(sym, expr)
__fb_unquote__(__fb_eval__("#undef " + sym))
__fb_unquote__(__fb_eval__("#define " + sym + " " + __fb_quote__(__fb_eval__(expr))))
#endmacro
#define a, b, x
assign("a", 8)
assign("b", 7)
assign("x", Sqr(a) + (Sin(b*3)/2))
Print x
assign("x", "goodbye")
Print x
Sleep
| f = loadstring(s)
one = loadstring"return 1"
two = loadstring"return ..."
|
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | #macro assign(sym, expr)
__fb_unquote__(__fb_eval__("#undef " + sym))
__fb_unquote__(__fb_eval__("#define " + sym + " " + __fb_quote__(__fb_eval__(expr))))
#endmacro
#define a, b, x
assign("a", 8)
assign("b", 7)
assign("x", Sqr(a) + (Sin(b*3)/2))
Print x
assign("x", "goodbye")
Print x
Sleep
| f = loadstring(s)
one = loadstring"return 1"
two = loadstring"return ..."
|
Keep all operations the same but rewrite the snippet in Lua. | Dim As Uinteger n, num
Print "First 20 Cullen numbers:"
For n = 1 To 20
num = n * (2^n)+1
Print num; " ";
Next
Print !"\n\nFirst 20 Woodall numbers:"
For n = 1 To 20
num = n * (2^n)-1
Print num; " ";
Next n
Sleep
| function T(t) return setmetatable(t, {__index=table}) end
table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end
table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end
function cullen(n) return (n<<n)+1 end
print("First 20 Cullen numbers:")
print(T{}:range(20):map(culle... |
Port the following code from VB to Lua with equivalent syntax and logic. | Const wheel="ndeokgelw"
Sub print(s):
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
Dim oDic
Set oDic = WScript.CreateObject("scripting.dictionary")
Dim cnt(127)
Dim fso
Set fso = WScript.CreateObject("Sc... | LetterCounter = {
new = function(self, word)
local t = { word=word, letters={} }
for ch in word:gmatch(".") do t.letters[ch] = (t.letters[ch] or 0) + 1 end
return setmetatable(t, self)
end,
contains = function(self, other)
for k,v in pairs(other.letters) do
if (self.letters[k] or 0) < v then... |
Write a version of this VB function in Lua with identical behavior. | Module Module1
Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)
Dim out As New List(Of String)
Dim comma = False
While Not String.IsNullOrEmpty(s)
Dim gs = GetItem(s, depth)
Dim g = gs.Item1
s = gs.Item2
If... | local function wrapEachItem(items, prefix, suffix)
local itemsWrapped = {}
for i, item in ipairs(items) do
itemsWrapped[i] = prefix .. item .. suffix
end
return itemsWrapped
end
local function getAllItemCombinationsConcatenated(aItems, bItems)
local combinations = {}
for _, a in ipairs(aItems) do
for _, b... |
Transform the following VB implementation into Lua, maintaining the same output and logic. | Public Sub circles()
tests = [{0.1234, 0.9876, 0.8765, 0.2345, 2.0; 0.0000, 2.0000, 0.0000, 0.0000, 1.0; 0.1234, 0.9876, 0.1234, 0.9876, 2.0; 0.1234, 0.9876, 0.8765, 0.2345, 0.5; 0.1234, 0.9876, 0.1234, 0.9876, 0.0}]
For i = 1 To UBound(tests)
x1 = tests(i, 1)
y1 = tests(i, 2)
x2 = tests... | function distance(p1, p2)
local dx = (p1.x-p2.x)
local dy = (p1.y-p2.y)
return math.sqrt(dx*dx + dy*dy)
end
function findCircles(p1, p2, radius)
local seperation = distance(p1, p2)
if seperation == 0.0 then
if radius == 0.0 then
print("No circles can be drawn through ("..p1.x.."... |
Write the same code in Lua as shown below in VB. | Public Sub circles()
tests = [{0.1234, 0.9876, 0.8765, 0.2345, 2.0; 0.0000, 2.0000, 0.0000, 0.0000, 1.0; 0.1234, 0.9876, 0.1234, 0.9876, 2.0; 0.1234, 0.9876, 0.8765, 0.2345, 0.5; 0.1234, 0.9876, 0.1234, 0.9876, 0.0}]
For i = 1 To UBound(tests)
x1 = tests(i, 1)
y1 = tests(i, 2)
x2 = tests... | function distance(p1, p2)
local dx = (p1.x-p2.x)
local dy = (p1.y-p2.y)
return math.sqrt(dx*dx + dy*dy)
end
function findCircles(p1, p2, radius)
local seperation = distance(p1, p2)
if seperation == 0.0 then
if radius == 0.0 then
print("No circles can be drawn through ("..p1.x.."... |
Maintain the same structure and functionality when rewriting this code in Lua. | option explicit
class playingcard
dim suit
dim pips
public sub print
dim s,p
select case suit
case "S":s=chrW(&h2660)
case "D":s=chrW(&h2666)
case "C":s=chrW(&h2663)
case "H":s=chrW(&h2665)
end select
select case pips
case 1:p="A"
case 11:p="J"
case 12:p="Q"
case 13:p="K"
case else:... |
function valid (t)
if #t ~= 5 then return false end
for k, v in pairs(t) do
for key, card in pairs(t) do
if v.value == card.value and
v.suit == card.suit and
k ~= key
then
return false
end
end
end
retur... |
Write a version of this VB function in Lua with identical behavior. | option explicit
class playingcard
dim suit
dim pips
public sub print
dim s,p
select case suit
case "S":s=chrW(&h2660)
case "D":s=chrW(&h2666)
case "C":s=chrW(&h2663)
case "H":s=chrW(&h2665)
end select
select case pips
case 1:p="A"
case 11:p="J"
case 12:p="Q"
case 13:p="K"
case else:... |
function valid (t)
if #t ~= 5 then return false end
for k, v in pairs(t) do
for key, card in pairs(t) do
if v.value == card.value and
v.suit == card.suit and
k ~= key
then
return false
end
end
end
retur... |
Change the programming language of this snippet from VB to Lua without modifying what it does. | Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Const HT As String = "H T"
Public Sub PenneysGame()
Dim S$, YourSeq$, ComputeSeq$, i&, Seq$, WhoWin$, flag As Boolean
Do
S = WhoWillBeFirst(Choice("Who will be first"))
If S = "ABORT" Then Exit Do
... | function penny_game()
local player, computer = "", ""
function player_choose()
io.write( "Enter your sequence of three H and/or T: " )
local t = io.read():upper()
if #t > 3 then t = t:sub( 1, 3 )
elseif #t < 3 then return ""
end
for i = 1, 3 do
c = t:... |
Ensure the translated Lua code behaves exactly like the original VB snippet. | option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public pr... |
function sierpinski (tri, order)
local new, p, t = {}
if order > 0 then
for i = 1, #tri do
p = i + 2
if p > #tri then p = p - #tri end
new[i] = (tri[i] + tri[p]) / 2
end
sierpinski({tri[1],tri[2],new[1],new[2],new[5],new[6]}, order-1)
sierpins... |
Port the following code from VB to Lua with equivalent syntax and logic. | option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public pr... |
function sierpinski (tri, order)
local new, p, t = {}
if order > 0 then
for i = 1, #tri do
p = i + 2
if p > #tri then p = p - #tri end
new[i] = (tri[i] + tri[p]) / 2
end
sierpinski({tri[1],tri[2],new[1],new[2],new[5],new[6]}, order-1)
sierpins... |
Can you help me rewrite this code in Lua instead of VB, keeping it the same logically? | Module Module1
Structure Interval
Dim start As Integer
Dim last As Integer
Dim print As Boolean
Sub New(s As Integer, l As Integer, p As Boolean)
start = s
last = l
print = p
End Sub
End Structure
Sub Main()
Dim intervals... | function makeInterval(s,e,p)
return {start=s, end_=e, print_=p}
end
function main()
local intervals = {
makeInterval( 2, 1000, true),
makeInterval(1000, 4000, true),
makeInterval( 2, 10000, false),
makeInterval( 2, 1000000, false),
makeInterval(... |
Produce a language-to-language conversion: from VB to Lua, same semantics. | Module Module1
Structure Interval
Dim start As Integer
Dim last As Integer
Dim print As Boolean
Sub New(s As Integer, l As Integer, p As Boolean)
start = s
last = l
print = p
End Sub
End Structure
Sub Main()
Dim intervals... | function makeInterval(s,e,p)
return {start=s, end_=e, print_=p}
end
function main()
local intervals = {
makeInterval( 2, 1000, true),
makeInterval(1000, 4000, true),
makeInterval( 2, 10000, false),
makeInterval( 2, 1000000, false),
makeInterval(... |
Rewrite the snippet below in Lua so it works the same as the original VB code. | Option Explicit
Public Sub coconuts()
Dim sailors As Integer
Dim share As Long
Dim finalshare As Integer
Dim minimum As Long, pile As Long
Dim i As Long, j As Integer
Debug.Print "Sailors", "Pile", "Final share"
For sailors = 2 To 6
i = 1
Do While True
pile = i
... | function valid(n,nuts)
local k = n
local i = 0
while k ~= 0 do
if (nuts % n) ~= 1 then
return false
end
k = k - 1
nuts = nuts - 1 - math.floor(nuts / n)
end
return nuts ~= 0 and (nuts % n == 0)
end
for n=2, 9 do
local x = 0
while not valid(n, x) d... |
Rewrite the snippet below in Lua so it works the same as the original VB code. | Option Explicit
Public Sub coconuts()
Dim sailors As Integer
Dim share As Long
Dim finalshare As Integer
Dim minimum As Long, pile As Long
Dim i As Long, j As Integer
Debug.Print "Sailors", "Pile", "Final share"
For sailors = 2 To 6
i = 1
Do While True
pile = i
... | function valid(n,nuts)
local k = n
local i = 0
while k ~= 0 do
if (nuts % n) ~= 1 then
return false
end
k = k - 1
nuts = nuts - 1 - math.floor(nuts / n)
end
return nuts ~= 0 and (nuts % n == 0)
end
for n=2, 9 do
local x = 0
while not valid(n, x) d... |
Can you help me rewrite this code in Lua instead of VB, keeping it the same logically? | Option Explicit
Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long
Sub Musical_Scale()
Dim Fqs, i As Integer
Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)
For i = LBound(Fqs) To UBound(Fqs)
Beep Fqs(i), 500
Next
End Sub
| c = string.char
midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96)
midi = midi .. "MTrk" .. c(0,0,0,8*8+4)
for _,note in ipairs{60,62,64,65,67,69,71,72} do
midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0)
end
midi = midi .. c(0, 0xFF, 0x2F, 0)
file = io.open("scale.mid", "wb")
file:write(midi)
file:close()
mid... |
Convert this VB block to Lua, preserving its control flow and logic. | Option Explicit
Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long
Sub Musical_Scale()
Dim Fqs, i As Integer
Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)
For i = LBound(Fqs) To UBound(Fqs)
Beep Fqs(i), 500
Next
End Sub
| c = string.char
midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96)
midi = midi .. "MTrk" .. c(0,0,0,8*8+4)
for _,note in ipairs{60,62,64,65,67,69,71,72} do
midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0)
end
midi = midi .. c(0, 0xFF, 0x2F, 0)
file = io.open("scale.mid", "wb")
file:write(midi)
file:close()
mid... |
Write the same code in Lua as shown below in VB. | Set objXMLDoc = CreateObject("msxml2.domdocument")
objXMLDoc.load("In.xml")
Set item_nodes = objXMLDoc.selectNodes("//item")
i = 1
For Each item In item_nodes
If i = 1 Then
WScript.StdOut.Write item.xml
WScript.StdOut.WriteBlankLines(2)
Exit For
End If
Next
Set price_nodes = objXMLDoc.selectNodes("//price")
... | require 'lxp'
data = [[<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitatio... |
Produce a functionally identical Lua code for the snippet given in VB. | Sub Main()
Dim HttpReq As WinHttp.WinHttpRequest
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 As Long = &H80&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 As Long = &H200&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 As Long = &H800&
Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2
#Const USE_PROXY = 1
Set Http... | local requests = require('requests')
local auth = requests.HTTPBasicAuth('admin', 'admin')
local resp, e = requests.get({
url = 'https://httpbin.org/basic-auth/admin/admin',
auth = auth
})
io.write(string.format('Status: %d', resp.status_code))
|
Rewrite the snippet below in Lua so it works the same as the original VB code. |
Function encrypt(ByVal originalText, ByVal alphabet, blank1, blank2)
Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ."
Dim i, j, curChar, escChar, outText
Dim cipher
Set cipher = CreateObject("Scripting.Dictionary")
alphabet = UCase(alphabet) : j = 0
For i = 1 To 28
curChar = Mid(alphabet... | local brd = { "HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./" }
local dicE, dicD, s1, s2 = {}, {}, 0, 0
function dec( txt )
local i, numb, s, t, c = 1, false
while( i < #txt ) do
c = txt:sub( i, i )
if not numb then
if tonumber( c ) == s1 then
i = i + 1; s = string.format( ... |
Write a version of this VB function in Lua with identical behavior. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1,False,0)
cei = 0 : cie = 0 : ei = 0 : ie = 0
Do Until srcFile.AtEndOfStream
word = srcFile.ReadLine
If InStr(word,"cei") Then
cei = cei + 1
ElseIf In... |
local http = require("socket.http")
function count (pattern, wordList)
local total = 0
for word in wordList:gmatch("%S+") do
if word:match(pattern) then total = total + 1 end
end
return total
end
function plaus (case, opposite, words)
if count(case, words) > 2 * count(opposite, words) t... |
Write a version of this VB function in Lua with identical behavior. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1,False,0)
cei = 0 : cie = 0 : ei = 0 : ie = 0
Do Until srcFile.AtEndOfStream
word = srcFile.ReadLine
If InStr(word,"cei") Then
cei = cei + 1
ElseIf In... |
local http = require("socket.http")
function count (pattern, wordList)
local total = 0
for word in wordList:gmatch("%S+") do
if word:match(pattern) then total = total + 1 end
end
return total
end
function plaus (case, opposite, words)
if count(case, words) > 2 * count(opposite, words) t... |
Convert the following code from VB to Lua, ensuring the logic remains intact. | Private Sub sierpinski(Order_ As Integer, Side As Double)
Dim Circumradius As Double, Inradius As Double
Dim Height As Double, Diagonal As Double, HeightDiagonal As Double
Dim Pi As Double, p(5) As String, Shp As Shape
Circumradius = Sqr(50 + 10 * Sqr(5)) / 10
Inradius = Sqr(25 + 10 * Sqr(5)) / 10
... | Bitmap.chaosgame = function(self, n, r, niters)
local w, h, vertices = self.width, self.height, {}
for i = 1, n do
vertices[i] = {
x = w/2 + w/2 * math.cos(math.pi/2+(i-1)*math.pi*2/n),
y = h/2 - h/2 * math.sin(math.pi/2+(i-1)*math.pi*2/n)
}
end
local x, y = w/2, h/2
for i = 1, niters do
... |
Write the same code in Lua as shown below in VB. | Public n As Variant
Private Sub init()
n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]
End Sub
Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant
Dim wtb As Integer
Dim bn As Integer
Dim prev As String: prev = "#"
Dim next_ As String
Dim p2468 As Str... | function zhangSuenThin(img)
local dirs={
{ 0,-1},
{ 1,-1},
{ 1, 0},
{ 1, 1},
{ 0, 1},
{-1, 1},
{-1, 0},
{-1,-1},
{ 0,-1},
}
local black=1
local white=0
function A(x, y)
local c=0
local current=img[y+dirs[1][2]]... |
Convert this VB block to Lua, preserving its control flow and logic. | Module Module1
Structure Point
Implements IComparable(Of Point)
Public Sub New(mx As Double, my As Double)
X = mx
Y = my
End Sub
Public ReadOnly Property X As Double
Public ReadOnly Property Y As Double
Public Function CompareTo(other As Po... | EPS = 1e-14
function pts(p)
local x, y = p.x, p.y
if x == 0 then
x = 0
end
if y == 0 then
y = 0
end
return "(" .. x .. ", " .. y .. ")"
end
function lts(pl)
local str = "["
for i,p in pairs(pl) do
if i > 1 then
str = str .. ", "
end
s... |
Maintain the same structure and functionality when rewriting this code in Lua. | Module Module1
Dim atomicMass As New Dictionary(Of String, Double) From {
{"H", 1.008},
{"He", 4.002602},
{"Li", 6.94},
{"Be", 9.0121831},
{"B", 10.81},
{"C", 12.011},
{"N", 14.007},
{"O", 15.999},
{"F", 18.998403163},
{"Ne", 20.1797},... | atomicMass = {
["H"] = 1.008,
["He"] = 4.002602,
["Li"] = 6.94,
["Be"] = 9.0121831,
["B"] = 10.81,
["C"] = 12.011,
["N"] = 14.007,
["O"] = 15.999,
["F"] = 18.998403163,
["Ne"] = 20.1797,
["Na"] = 22.98976928,
["Mg"] = 24.305,
["Al"] ... |
Translate this program into Lua but keep the logic exactly as in VB. | Module Module1
ReadOnly SNL As New Dictionary(Of Integer, Integer) From {
{4, 14},
{9, 31},
{17, 7},
{20, 38},
{28, 84},
{40, 59},
{51, 67},
{54, 34},
{62, 19},
{63, 81},
{64, 60},
{71, 91},
{87, 24},
{9... | local sixesThrowAgain = true
function rollDice()
return math.random(6)
end
function nextSquare(square)
if square == 4 then
return 14
elseif square == 9 then
return 31
elseif square == 17 then
return 7
elseif square == 20 then
return 38
elseif square == 28 then
... |
Write the same algorithm in Lua as shown in this VB implementation. | Module Module1
ReadOnly SNL As New Dictionary(Of Integer, Integer) From {
{4, 14},
{9, 31},
{17, 7},
{20, 38},
{28, 84},
{40, 59},
{51, 67},
{54, 34},
{62, 19},
{63, 81},
{64, 60},
{71, 91},
{87, 24},
{9... | local sixesThrowAgain = true
function rollDice()
return math.random(6)
end
function nextSquare(square)
if square == 4 then
return 14
elseif square == 9 then
return 31
elseif square == 17 then
return 7
elseif square == 20 then
return 38
elseif square == 28 then
... |
Please provide an equivalent version of this VB code in Lua. | Dim dblDistance as Double
| local DISTANCE_MAXIMUM = 1
local distance_to_target = 0
local function distanceToTarget() end
local function TargetFactory() end
for _,v in ipairs(table) do
print(v)
end
|
Generate a Lua translation of this VB snippet without changing its computational steps. | Function farey(n As Long, descending As Long) As Long
Dim a, b, c, d, k As Long
Dim aa, bb, cc, dd, count As Long
b = 1
c = 1
d = n
count = 0
If descending = True Then
a = 1
c = n - 1
End If
count += 1
If n < 12 Then Print Str(a); "/"; Str(b); " ";
While ((c <= n) And... |
function farey (n)
local a, b, c, d, k = 0, 1, 1, n
local farTab = {{a, b}}
while c <= n do
k = math.floor((n + b) / d)
a, b, c, d = c, d, k * c - a, k * d - b
table.insert(farTab, {a, b})
end
return farTab
end
for i = 1, 11 do
io.write(i .. ": ")
for _, frac in pa... |
Please provide an equivalent version of this VB code in Lua. | Function farey(n As Long, descending As Long) As Long
Dim a, b, c, d, k As Long
Dim aa, bb, cc, dd, count As Long
b = 1
c = 1
d = n
count = 0
If descending = True Then
a = 1
c = n - 1
End If
count += 1
If n < 12 Then Print Str(a); "/"; Str(b); " ";
While ((c <= n) And... |
function farey (n)
local a, b, c, d, k = 0, 1, 1, n
local farTab = {{a, b}}
while c <= n do
k = math.floor((n + b) / d)
a, b, c, d = c, d, k * c - a, k * d - b
table.insert(farTab, {a, b})
end
return farTab
end
for i = 1, 11 do
io.write(i .. ": ")
for _, frac in pa... |
Convert the following code from VB to Lua, ensuring the logic remains intact. | Imports System.Numerics
Module Module1
Function Sqrt(x As BigInteger) As BigInteger
If x < 0 Then
Throw New ArgumentException("Negative argument.")
End If
If x < 2 Then
Return x
End If
Dim y = x / 2
While y > (x / y)
y = ((x / y) ... |
function isPrime (x)
if x < 2 then return false end
if x < 4 then return true end
if x % 2 == 0 then return false end
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
local i, p = 0
repeat
i = i + 1
p = 2 ^ i - 1
if isPrime(p) then
print("2 ^ " .. i .. "... |
Please provide an equivalent version of this VB code in Lua. | Imports System.Numerics
Module Module1
Function Sqrt(x As BigInteger) As BigInteger
If x < 0 Then
Throw New ArgumentException("Negative argument.")
End If
If x < 2 Then
Return x
End If
Dim y = x / 2
While y > (x / y)
y = ((x / y) ... |
function isPrime (x)
if x < 2 then return false end
if x < 4 then return true end
if x % 2 == 0 then return false end
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
local i, p = 0
repeat
i = i + 1
p = 2 ^ i - 1
if isPrime(p) then
print("2 ^ " .. i .. "... |
Ensure the translated Lua code behaves exactly like the original VB snippet. | Public Type tuple
i As Variant
j As Variant
sum As Variant
End Type
Public Type tuple3
i1 As Variant
j1 As Variant
i2 As Variant
j2 As Variant
i3 As Variant
j3 As Variant
sum As Variant
End Type
Sub taxicab_numbers()
Dim i As Variant, j As Variant
Dim k As Long
Const ... | sums, taxis, limit = {}, {}, 1200
for i = 1, limit do
for j = 1, i-1 do
sum = i^3 + j^3
sums[sum] = sums[sum] or {}
table.insert(sums[sum], i.."^3 + "..j.."^3")
end
end
for k,v in pairs(sums) do
if #v > 1 then table.insert(taxis, { sum=k, num=#v, terms=table.concat(v," = ") }) end
end
table.sort(taxis... |
Produce a language-to-language conversion: from VB to Lua, same semantics. | Module Module1
Function Sieve(limit As Long) As List(Of Long)
Dim primes As New List(Of Long) From {2}
Dim c(limit + 1) As Boolean
Dim p = 3L
While True
Dim p2 = p * p
If p2 > limit Then
Exit While
End If
For i = p2 To ... | function squareFree (n)
for root = 2, math.sqrt(n) do
if n % (root * root) == 0 then return false end
end
return true
end
function run (lo, hi, showValues)
io.write("From " .. lo .. " to " .. hi)
io.write(showValues and ":\n" or " = ")
local count = 0
for i = lo, hi do
if squareFree(i) then
... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | Const n = 2200
Public Sub pq()
Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3
Dim l(n) As Boolean, l_add(9680000) As Boolean
For x = 1 To n
x2 = x * x
For y = x To n
l_add(x2 + y * y) = True
Next y
Next x
For x = 1 To n
s1 ... |
local N = 2200
local ar = {}
for i=1,N do
ar[i] = false
end
for a=1,N do
for b=a,N do
if (a % 2 ~= 1) or (b % 2 ~= 1) then
local aabb = a * a + b * b
for c=b,N do
local aabbcc = aabb + c * c
local d = math.floor(math.sqrt(aabbcc))
... |
Change the following VB code into Lua without altering its purpose. | #define isInteger(x) iif(Int(val(x)) = val(x), 1, 0)
Dim As String test(1 To 8) = {"25.000000", "24.999999", "25.000100", "-2.1e120", "-5e-2", "NaN", "Inf", "-0.05"}
For i As Integer = 1 To Ubound(test)
Dim As String s = test(i)
Print s,
If isInteger(s) then Print "is integer" Else Print "is not int... | function isInt (x) return type(x) == "number" and x == math.floor(x) end
print("Value\tInteger?")
print("=====\t========")
local testCases = {2, 0, -1, 3.5, "String!", true}
for _, input in pairs(testCases) do print(input, isInt(input)) end
|
Ensure the translated Lua code behaves exactly like the original VB snippet. |
#macro typeDetector(arg)
#if TypeOf(foo) = TypeOf(Byte)
Print arg; " -> It
#elseif TypeOf(foo) = TypeOf(Short)
Print arg; " -> It
#elseif TypeOf(foo) = TypeOf(Integer)
Print arg; " -> It
#elseif TypeOf(foo) = TypeOf(LongInt)
Print arg; " -> It
#elseif TypeOf(foo) = TypeO... | function writeValue(v)
local t = type(v)
if t == "number" then
io.write(v)
elseif t == "string" then
io.write("`" .. v .. "`")
elseif t == "table" then
local c = 0
io.write("{")
for k,v in pairs(v) do
if c > 0 then
io.write(", ")
... |
Translate the given VB code snippet into Lua without altering its behavior. | Imports System.Console
Namespace safety
Module SafePrimes
Dim pri_HS As HashSet(Of Integer) = Primes(10_000_000).ToHashSet()
Sub Main()
For Each UnSafe In {False, True} : Dim n As Integer = If(UnSafe, 40, 35)
WriteLine($"The first {n} {If(UnSafe, "un", "")}safe primes a... |
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end
table.firstn = function(t,n) local s=T{} n=n>#... |
Maintain the same structure and functionality when rewriting this code in Lua. | Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"
Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1... | local function recA(age, name) return { Age=age, Name=name } end
local tabA = { recA(27,"Jonah"), recA(18,"Alan"), recA(28,"Glory"), recA(18,"Popeye"), recA(28,"Alan") }
local function recB(character, nemesis) return { Character=character, Nemesis=nemesis } end
local tabB = { recB("Jonah","Whales"), recB("Jonah","Spid... |
Write a version of this VB function in Lua with identical behavior. | Sub InsertaElto(lista() As String, posic As Integer = 1)
For i As Integer = Lbound(lista) To Ubound(lista)
If i = posic Then Swap lista(i), lista(Ubound(lista))
Next i
End Sub
Sub mostrarLista(lista() As String, titulo As String)
Print !"\n"; titulo;
For i As Integer = Lbound(lista) To Ubo... |
local function Node(data)
return { data=data }
end
local List = {
head = nil,
tail = nil,
insertHead = function(self, data)
local node = Node(data)
if (self.head) then
self.head.prev = node
node.next = self.head
self.head = node
else
self.head = node
self.tail = ... |
Generate a Lua translation of this VB snippet without changing its computational steps. | Imports System.Numerics
Module Module1
Sub Main()
Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
Dim one As BigInteger = 1
Dim nine As BigInteger = 9
For ii = 2 To 9
Console.WriteLine("First 10 super-{0} numbers:", ii)
... | for d = 2, 5 do
local n, found = 0, {}
local dds = string.rep(d, d)
while #found < 10 do
local dnd = string.format("%15.f", d * n ^ d)
if string.find(dnd, dds) then found[#found+1] = n end
n = n + 1
end
print("super-" .. d .. ": " .. table.concat(found,", "))
end
|
Maintain the same structure and functionality when rewriting this code in Lua. | Imports System.Numerics
Module Module1
Sub Main()
Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
Dim one As BigInteger = 1
Dim nine As BigInteger = 9
For ii = 2 To 9
Console.WriteLine("First 10 super-{0} numbers:", ii)
... | for d = 2, 5 do
local n, found = 0, {}
local dds = string.rep(d, d)
while #found < 10 do
local dnd = string.format("%15.f", d * n ^ d)
if string.find(dnd, dds) then found[#found+1] = n end
n = n + 1
end
print("super-" .. d .. ": " .. table.concat(found,", "))
end
|
Maintain the same structure and functionality when rewriting this code in Lua. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1)
Set objKeyMap = CreateObject("Scripting.Dictionary")
With objKeyMap
.Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5"
.Add "MNO",... |
http = require("socket.http")
keys = {"VOICEMAIL", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
dictFile = "http://www.puzzlers.org/pub/wordlists/unixdict.txt"
function keySequence (str)
local sequence, noMatch, letter = ""
for pos = 1, #str do
letter = str:sub(pos, pos)
for i, c... |
Port the following code from VB to Lua with equivalent syntax and logic. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = Da... | cycles = {"Physical day ", "Emotional day", "Mental day "}
lengths = {23, 28, 33}
quadrants = {
{"up and rising", "peak"},
{"up but falling", "transition"},
{"down and falling", "valley"},
{"down but rising", "transition"},
}
function parse_date_string (birthDate)
local year, month, day = birthDate:match("(%d+... |
Translate this program into Lua but keep the logic exactly as in VB. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = Da... | cycles = {"Physical day ", "Emotional day", "Mental day "}
lengths = {23, 28, 33}
quadrants = {
{"up and rising", "peak"},
{"up but falling", "transition"},
{"down and falling", "valley"},
{"down but rising", "transition"},
}
function parse_date_string (birthDate)
local year, month, day = birthDate:match("(%d+... |
Write the same code in Lua as shown below in VB. | function isprime(v)
if v mod 2 = 0 then return v = 2
for d = 3 To Int(Sqr(v))+1 Step 2
if v mod d = 0 then return false
next d3
return True
end function
function diff_cubes(n)
return 3*n*(n+1) + 1
end function
function padto(n, s)
outstr = ""
k = length(string(n))
for i = 1 to s-k
outstr = " " + outstr
n... | local primes = {3, 5}
local cutOff = 200
local bigUn = 100000
local chunks = 50
local little = math.floor(bigUn / chunks)
local tn = " cuban prime"
print(string.format("The first %d%ss", cutOff, tn))
local showEach = true
local c = 0
local u = 0
local v = 1
for i=1,10000000000000 do
local found = false
u = u + ... |
Please provide an equivalent version of this VB code in Lua. | Imports System.Text
Module Module1
Dim games As New List(Of String) From {"12", "13", "14", "23", "24", "34"}
Dim results = "000000"
Function FromBase3(num As String) As Integer
Dim out = 0
For Each c In num
Dim d = Asc(c) - Asc("0"c)
out = 3 * out + d
Next... | function array1D(a, d)
local m = {}
for i=1,a do
table.insert(m, d)
end
return m
end
function array2D(a, b, d)
local m = {}
for i=1,a do
table.insert(m, array1D(b, d))
end
return m
end
function fromBase3(num)
local out = 0
for i=1,#num do
local c = num:s... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | Module Module1
Class SymbolType
Public ReadOnly symbol As String
Public ReadOnly precedence As Integer
Public ReadOnly rightAssociative As Boolean
Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)
Me.symbol = symbol
Me.prece... |
local OPERATOR_PRECEDENCE = {
['-'] = { 2, true };
['+'] = { 2, true };
['/'] = { 3, true };
['*'] = { 3, true };
['^'] = { 4, false };
}
local function shuntingYard(expression)
local outputQueue = { }
local operatorStack = { }
local number, operator, parenthesis, fcall
... |
Rewrite the snippet below in Lua so it works the same as the original VB code. | Type vector
x As Double
y As Double
End Type
Type vector2
phi As Double
r As Double
End Type
Private Function vector_addition(u As vector, v As vector) As vector
vector_addition.x = u.x + v.x
vector_addition.y = u.y + v.y
End Function
Private Function vector_subtraction(u As vector, v As vector)... | vector = {mt = {}}
function vector.new (x, y)
local new = {x = x or 0, y = y or 0}
setmetatable(new, vector.mt)
return new
end
function vector.mt.__add (v1, v2)
return vector.new(v1.x + v2.x, v1.y + v2.y)
end
function vector.mt.__sub (v1, v2)
return vector.new(v1.x - v2.x, v1.y - v2.y)
end
func... |
Generate an equivalent Lua version of this VB code. |
Dim coef(10),cheby(10)
pi=4*Atn(1)
a=0: b=1: n=10
For i=0 To n-1
coef(i)=Cos(Cos(pi/n*(i+1/2))*(b-a)/2+(b+a)/2)
Next
For i=0 To n-1
w=0
For j=0 To n-1
w=w+coef(j)*Cos(pi/n*i*(j+1/2))
Next
cheby(i)=w*2/n
If cheby(i)<=0 Then t="" Else t=" "
WScript.StdOut.WriteLine i&" : "&t... | function map(x, min_x, max_x, min_to, max_to)
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
end
function chebyshevCoef(func, minn, maxx, coef)
local N = table.getn(coef)
for j=1,N do
local i = j - 1
local m = map(math.cos(math.pi * (i + 0.5) / N), -1, 1, minn, maxx)
... |
Rewrite the snippet below in Lua so it works the same as the original VB code. |
Dim coef(10),cheby(10)
pi=4*Atn(1)
a=0: b=1: n=10
For i=0 To n-1
coef(i)=Cos(Cos(pi/n*(i+1/2))*(b-a)/2+(b+a)/2)
Next
For i=0 To n-1
w=0
For j=0 To n-1
w=w+coef(j)*Cos(pi/n*i*(j+1/2))
Next
cheby(i)=w*2/n
If cheby(i)<=0 Then t="" Else t=" "
WScript.StdOut.WriteLine i&" : "&t... | function map(x, min_x, max_x, min_to, max_to)
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
end
function chebyshevCoef(func, minn, maxx, coef)
local N = table.getn(coef)
for j=1,N do
local i = j - 1
local m = map(math.cos(math.pi * (i + 0.5) / N), -1, 1, minn, maxx)
... |
Convert this VB snippet to Lua and keep its semantics consistent. | Module Module1
ReadOnly STX As Char = Chr(&H2)
ReadOnly ETX As Char = Chr(&H3)
Sub Rotate(Of T)(a As T())
Dim o = a.Last
For i = a.Length - 1 To 1 Step -1
a(i) = a(i - 1)
Next
a(0) = o
End Sub
Private Function Compare(s1 As String, s2 As String) As Inte... | STX = string.char(tonumber(2,16))
ETX = string.char(tonumber(3,16))
function bwt(s)
if s:find(STX, 1, true) then
error("String cannot contain STX")
end
if s:find(ETX, 1, true) then
error("String cannot contain ETX")
end
local ss = STX .. s .. ETX
local tbl = {}
for i=1,#ss ... |
Convert the following code from VB to Lua, ensuring the logic remains intact. | Module Module1
ReadOnly STX As Char = Chr(&H2)
ReadOnly ETX As Char = Chr(&H3)
Sub Rotate(Of T)(a As T())
Dim o = a.Last
For i = a.Length - 1 To 1 Step -1
a(i) = a(i - 1)
Next
a(0) = o
End Sub
Private Function Compare(s1 As String, s2 As String) As Inte... | STX = string.char(tonumber(2,16))
ETX = string.char(tonumber(3,16))
function bwt(s)
if s:find(STX, 1, true) then
error("String cannot contain STX")
end
if s:find(ETX, 1, true) then
error("String cannot contain ETX")
end
local ss = STX .. s .. ETX
local tbl = {}
for i=1,#ss ... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | Imports System.Runtime.CompilerServices
Imports System.Text
Module Module1
<Extension()>
Function AsString(Of T)(c As ICollection(Of T)) As String
Dim sb = New StringBuilder("[")
sb.Append(String.Join(", ", c))
Return sb.Append("]").ToString()
End Function
Private rand As New ... |
function newDeck ()
local cards, suits = {}, {"C", "D", "H", "S"}
for _, suit in pairs(suits) do
for value = 2, 14 do
if value == 10 then value = "T" end
if value == 11 then value = "J" end
if value == 12 then value = "Q" end
if value == 13 then value = "... |
Produce a language-to-language conversion: from VB to Lua, same semantics. | Imports System.Runtime.CompilerServices
Imports System.Text
Module Module1
<Extension()>
Function AsString(Of T)(c As ICollection(Of T)) As String
Dim sb = New StringBuilder("[")
sb.Append(String.Join(", ", c))
Return sb.Append("]").ToString()
End Function
Private rand As New ... |
function newDeck ()
local cards, suits = {}, {"C", "D", "H", "S"}
for _, suit in pairs(suits) do
for value = 2, 14 do
if value == 10 then value = "T" end
if value == 11 then value = "J" end
if value == 12 then value = "Q" end
if value == 13 then value = "... |
Change the following VB code into Lua without altering its purpose. | Module Module1
Class Frac
Private ReadOnly num As Long
Private ReadOnly denom As Long
Public Shared ReadOnly ZERO = New Frac(0, 1)
Public Shared ReadOnly ONE = New Frac(1, 1)
Public Sub New(n As Long, d As Long)
If d = 0 Then
Throw New ArgumentE... | function binomial(n,k)
if n<0 or k<0 or n<k then return -1 end
if n==0 or k==0 then return 1 end
local num = 1
for i=k+1,n do
num = num * i
end
local denom = 1
for i=2,n-k do
denom = denom * i
end
return num / denom
end
function gcd(a,b)
while b ~= 0 do
... |
Generate an equivalent Lua version of this VB code. | Module Module1
Function Gcd(a As Long, b As Long)
If b = 0 Then
Return a
End If
Return Gcd(b, a Mod b)
End Function
Class Frac
ReadOnly num As Long
ReadOnly denom As Long
Public Shared ReadOnly ZERO As New Frac(0, 1)
Public Shared ReadOnl... | function binomial(n,k)
if n<0 or k<0 or n<k then return -1 end
if n==0 or k==0 then return 1 end
local num = 1
for i=k+1,n do
num = num * i
end
local denom = 1
for i=2,n-k do
denom = denom * i
end
return num / denom
end
function gcd(a,b)
while b ~= 0 do
... |
Produce a language-to-language conversion: from VB to Lua, same semantics. | Option Explicit
Sub Main()
Dim Dict As Object, L() As Long
Dim t As Single
Init Dict
L = ListPrimes(100000000)
t = Timer
PrimeConspiracy L, Dict, 1000000
Debug.Print "----------------------------"
Debug.Print "Execution time : " & Format(Timer - t, "0.000s.")
Debug.Print ""
Init Dict
t = Timer
PrimeCon... |
function isPrime (n)
if n <= 1 then return false end
if n <= 3 then return true end
if n % 2 == 0 or n % 3 == 0 then return false end
local i = 5
while i * i <= n do
if n % i == 0 or n % (i + 2) == 0 then return false end
i = i + 6
end
return true
end
function primeCon (l... |
Convert this VB block to Lua, preserving its control flow and logic. | Public Sub standard_normal()
Dim s() As Variant, bins(71) As Single
ReDim s(20000)
For i = 1 To 20000
s(i) = WorksheetFunction.Norm_S_Inv(Rnd())
Next i
For i = -35 To 35
bins(i + 36) = i / 10
Next i
Debug.Print "sample size"; UBound(s), "mean"; mean(s), "standard deviation"; ... | function gaussian (mean, variance)
return math.sqrt(-2 * variance * math.log(math.random())) *
math.cos(2 * math.pi * math.random()) + mean
end
function mean (t)
local sum = 0
for k, v in pairs(t) do
sum = sum + v
end
return sum / #t
end
function std (t)
local squares, a... |
Rewrite the snippet below in Lua so it works the same as the original VB code. | Imports System, System.Linq, System.Collections.Generic, System.Console
Module Module1
Dim fmt As String = "{0,4} * {1,31:n0} = {2,-28}" & vbLf
Sub B10(ByVal n As Integer)
If n <= 1 Then Return
Dim pow As Integer() = New Integer(n) {},
val As Integer() = New Integer(n) {},
... | function array1D(n, v)
local tbl = {}
for i=1,n do
table.insert(tbl, v)
end
return tbl
end
function array2D(h, w, v)
local tbl = {}
for i=1,h do
table.insert(tbl, array1D(w, v))
end
return tbl
end
function mod(m, n)
m = math.floor(m)
local result = m % n
if ... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | Module Module1
Dim resu As New List(Of Integer)
Function TestAbundant(n As Integer, ByRef divs As List(Of Integer)) As Boolean
divs = New List(Of Integer)
Dim sum As Integer = -n : For i As Integer = Math.Sqrt(n) To 1 Step -1
If n Mod i = 0 Then divs.Add(i) : Dim j As Integer = n /... | function make(n, d)
local a = {}
for i=1,n do
table.insert(a, d)
end
return a
end
function reverse(t)
local n = #t
local i = 1
while i < n do
t[i],t[n] = t[n],t[i]
i = i + 1
n = n - 1
end
end
function tail(list)
return { select(2, unpack(list)) }
end... |
Rewrite the snippet below in Lua so it works the same as the original VB code. | Module Module1
Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)
Dim result As New List(Of Integer) From {
n
}
result.AddRange(seq)
Return result
End Function
Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_... | function index(a,i)
return a[i + 1]
end
function checkSeq(pos, seq, n, minLen)
if pos > minLen or index(seq,0) > n then
return minLen, 0
elseif index(seq,0) == n then
return pos, 1
elseif pos < minLen then
return tryPerm(0, pos, seq, n, minLen)
else
return minLen, 0
... |
Keep all operations the same but rewrite the snippet in Lua. | Imports System.Reflection
Module Module1
Class TestClass
Private privateField = 7
Public ReadOnly Property PublicNumber = 4
Private ReadOnly Property PrivateNumber = 2
End Class
Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return From p ... | a = 1
b = 2.0
c = "hello world"
function listProperties(t)
if type(t) == "table" then
for k,v in pairs(t) do
if type(v) ~= "function" then
print(string.format("%7s: %s", type(v), k))
end
end
end
end
print("Global properties")
listProperties(_G)
print("Pa... |
Can you help me rewrite this code in Lua instead of VB, keeping it the same logically? | Module Module1
Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)
Dim size = g.Count
Dim vis(size - 1) As Boolean
Dim l(size - 1) As Integer
Dim x = size
Dim t As New List(Of List(Of Integer))
For i = 1 To size
t.Add(New List(Of Intege... | function write_array(a)
io.write("[")
for i=0,#a do
if i>0 then
io.write(", ")
end
io.write(tostring(a[i]))
end
io.write("]")
end
function kosaraju(g)
local size = #g
local vis = {}
for i=0,size do
vis[i] = false
end
local ... |
Can you help me rewrite this code in Lua instead of VB, keeping it the same logically? | Module Module1
Structure Node
Private ReadOnly m_val As String
Private ReadOnly m_parsed As List(Of String)
Sub New(initial As String)
m_val = initial
m_parsed = New List(Of String)
End Sub
Sub New(s As String, p As List(Of String))
m_va... |
function genDict(ws)
local d,dup,head,rest = {},{}
for w in ws:gmatch"%w+" do
local lw = w:lower()
if not dup[lw] then
dup[lw], head,rest = true, lw:match"^(%w)(.-)$"
d[head] = d[head] or {n=-1}
local len = #rest
d[head][len] = d[head][len] or {}
d[head][len][rest] = true
... |
Write the same code in Lua as shown below in VB. | Option explicit
Class ImgClass
Private ImgL,ImgH,ImgDepth,bkclr,loc,tt
private xmini,xmaxi,ymini,ymaxi,dirx,diry
public ImgArray()
private filename
private Palette,szpal
public property get xmin():xmin=xmini:end property
public property get ymin():ymin=ymini:end property
public property ge... | local function hsv_to_rgb (h, s, v)
local r = math.min (math.max (3*math.abs (((h )/180)%2-1)-1, 0), 1)
local g = math.min (math.max (3*math.abs (((h -120)/180)%2-1)-1, 0), 1)
local b = math.min (math.max (3*math.abs (((h +120)/180)%2-1)-1, 0), 1)
local k1 = v*(1-s)
local k2 = v - k1
... |
Transform the following VB implementation into Lua, maintaining the same output and logic. | Imports System
Module Module1
Function dc8(ByVal n As Integer) As Boolean
Dim count, p, d As Integer, res As Integer = 1
While (n And 1) = 0 : n >>= 1 : res += 1 : End While
count = 1 : While n Mod 3 = 0 : n \= 3 : count += 1 : End While
p = 5 : d = 4 : While p * p <= n
... | function is_1_or_has_eight_divisors (n)
if n == 1 then return true end
local divCount, sqr = 2, math.sqrt(n)
for d = 2, sqr do
if n % d == 0 then
divCount = d == sqr and divCount + 1 or divCount + 2
end
if divCount > 8 then return false end
end
return divCount == ... |
Convert the following code from C to Arturo, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
#define otherwise do { register int _o = 2; do { switch (_o) { case 1:
#define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo());
... | ifStatement: function [block, condition][
if condition -> do block
]
alias.infix {??} 'ifStatement
do [
variable: true
[print "Variable is true!"] ?? variable
]
|
Translate the given C code snippet into Arturo without altering its behavior. | #include <stdio.h>
#include <stdlib.h>
#define otherwise do { register int _o = 2; do { switch (_o) { case 1:
#define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo());
... | ifStatement: function [block, condition][
if condition -> do block
]
alias.infix {??} 'ifStatement
do [
variable: true
[print "Variable is true!"] ?? variable
]
|
Port the provided C code into Arturo while preserving the original functionality. | #include <stdio.h>
#include <ctype.h>
char rfc3986[256] = {0};
char html5[256] = {0};
void encode(const char *s, char *enc, char *tb)
{
for (; *s; s++) {
if (tb[*s]) sprintf(enc, "%c", tb[*s]);
else sprintf(enc, "%%%02X", *s);
while (*++enc);
}
}
int main()
{
const char url[] = "http:
char enc[(s... | encoded: encode.url.slashes "http://foo bar/"
print encoded
|
Please provide an equivalent version of this C code in Arturo. | #include <stdio.h>
#include <ctype.h>
char rfc3986[256] = {0};
char html5[256] = {0};
void encode(const char *s, char *enc, char *tb)
{
for (; *s; s++) {
if (tb[*s]) sprintf(enc, "%c", tb[*s]);
else sprintf(enc, "%%%02X", *s);
while (*++enc);
}
}
int main()
{
const char url[] = "http:
char enc[(s... | encoded: encode.url.slashes "http://foo bar/"
print encoded
|
Can you help me rewrite this code in Arturo instead of C, keeping it the same logically? | #include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
typedef const char * String;
typedef struct sTable {
String * *rows;
int n_rows,n_cols;
} *Table;
typedef int (*CompareFctn)(String a, String b);
struct {
CompareFctn compare;
int column;
int ... | sortTable: function [tbl][
column: "0"
reversed?: false
unless null? c: <= attr 'column -> column: to :string c
unless null? attr 'reverse -> reversed?: true
result: new sort.by: column map tbl 'r [
to :dictionary flatten couple 0..dec size r r
]
if reversed? -> reverse 'result
... |
Write the same code in Arturo as shown below in C. | #include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >= 0; i-... | proc: function [x]->
((abs x) ^ 0.5) + 5 * x ^ 3
ask: function [msg][
to [:floating] first.n: 11 split.words strip input msg
]
loop reverse ask "11 numbers: " 'n [
result: proc n
print [n ":" (result > 400)? -> "TOO LARGE!" -> result]
]
|
Preserve the algorithm and functionality while converting the code from C to Arturo. | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
struct timeval start, last;
inline int64_t tv_to_u(struct timeval s)
{
return s.tv_sec * 1000000 + s.tv_usec;
}
inline struct timeval u_to_tv(int64_t x)
{
struct timeval s;
s.... | startMetronome: function [bpm,msr][
freq: 60000/bpm
i: 0
while [true][
loop msr-1 'x[
prints "\a"
pause freq
]
inc 'i
print ~"\aAND |i|"
pause freq
]
]
tempo: to :integer arg\0
beats: to :integer arg\1
startMetronome tempo beats
|
Write the same code in Arturo as shown below in C. | #include <stdio.h>
#include <string.h>
int repstr(char *str)
{
if (!str) return 0;
size_t sl = strlen(str) / 2;
while (sl > 0) {
if (strstr(str, str + sl) == str)
return sl;
--sl;
}
return 0;
}
int main(void)
{
char *strs[] = { "1001110011", "1110111011", "0010010... | repeated?: function [text][
loop ((size text)/2)..0 'x [
if prefix? text slice text x (size text)-1 [
(x>0)? -> return slice text 0 x-1
-> return false
]
]
return false
]
strings: {
1001110011
1110111011
0010010010
1010101010
1111111111
... |
Translate this program into Arturo but keep the logic exactly as in C. | #include <stdio.h>
#define MAX 15
int count_divisors(int n) {
int i, count = 0;
for (i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
int i, next = 1;
pr... | i: new 0
next: new 1
MAX: 15
while [next =< MAX][
if next = size factors i [
prints ~"|i| "
inc 'next
]
inc 'i
]
print ""
|
Preserve the algorithm and functionality while converting the code from C to Arturo. | #include <stdio.h>
int
main() {
int max = 0, i = 0, sixes, nines, twenties;
loopstart: while (i < 100) {
for (sixes = 0; sixes*6 < i; sixes++) {
if (sixes*6 == i) {
i++;
goto loopstart;
}
for (nines = 0; nines*9 < i; nines++) {
... | nonMcNuggets: function [lim][
result: new 0..lim
loop range.step:6 1 lim 'x [
loop range.step:9 1 lim 'y [
loop range.step:20 1 lim 'z
-> 'result -- sum @[x y z]
]
]
return result
]
print max nonMcNuggets 100
|
Write the same algorithm in Arturo as shown in this C implementation. | #include <stdio.h>
int main(int argc, char const *argv[]) {
for (char c = 0x41; c < 0x5b; c ++) putchar(c);
putchar('\n');
for (char c = 0x61; c < 0x7b; c ++) putchar(c);
putchar('\n');
return 0;
}
| print ["lowercase letters:" `a`..`z`]
print ["uppercase letters:" `A`..`Z`]
|
Write the same code in Arturo as shown below in C. | #include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
double jaro(const char *str1, const char *str2) {
int str1_len = strlen(str1);
int str2_len = strlen(str2)... | loop [
["MARTHA" "MARHTA"]
["DIXON" "DICKSONX"]
["JELLYFISH" "SMELLYFISH"]
] 'pair ->
print [pair "-> Jaro similarity:" round.to: 3 jaro first pair last pair]
|
Translate this program into Arturo but keep the logic exactly as in C. | #include <stdio.h>
unsigned int lpd(unsigned int n) {
if (n<=1) return 1;
int i;
for (i=n-1; i>0; i--)
if (n%i == 0) return i;
}
int main() {
int i;
for (i=1; i<=100; i++) {
printf("%3d", lpd(i));
if (i % 10 == 0) printf("\n");
}
return 0;
}
| loop split.every:10 [1] ++ map 2..100 'x -> last chop factors x 'row [
print map to [:string] row 'r -> pad r 5
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.