Boxlang 1.x Stable Released
BoxLang : A Modern Dynamic JVM Language
LogoLogo
APIDocsDownloadTrySourceSupport
  • Introduction
    • Contributing Guide
    • Release History
      • 1.1.0
      • 1.0.1
      • 1.0.0
      • RC Stage
        • 1.0.0-RC.1
        • 1.0.0-RC.2
        • 1.0.0-RC.3
      • Beta Stage
        • 1.0.0-Beta27
        • 1.0.0-Beta26
        • 1.0.0-Beta25
        • 1.0.0-Beta24
        • 1.0.0-Beta23
        • 1.0.0-Beta22
        • 1.0.0-Beta21
        • 1.0.0-Beta20
        • 1.0.0-Beta19
        • 1.0.0-Beta18
        • 1.0.0-Beta17
        • 1.0.0-Beta16
        • 1.0.0-Beta15
        • 1.0.0-Beta14
        • 1.0.0-Beta13
        • 1.0.0-Beta12
        • 1.0.0-Beta11
        • 1.0.0-Beta10
        • 1.0.0-Beta9
        • 1.0.0-Beta8
        • 1.0.0-Beta7
        • 1.0.0-Beta6
        • 1.0.0-Beta5
        • 1.0.0-Beta 4
        • 1.0.0-Beta3
        • 1.0.0-Beta2
    • About This Book
      • Authors
  • Getting Started
    • Overview
      • Multi-Runtime
      • Instructions & Interpreters
      • CommandBox CLI
      • Quick Syntax Guide
        • Differences From CFML
      • Frequently Asked Questions
      • Running ColdFusion/CFML Apps
        • Migrating from Adobe ColdFusion
        • Migrating From Lucee CFML
    • Installation
      • Modules
    • Running BoxLang
      • AWS Lambda
      • CommandBox
      • Chromebooks
      • CLI Scripting
      • Docker
      • JSR-223 Scripting
      • MiniServer
      • Try BoxLang!
    • BoxLang Cloud Servers
      • Microsoft Azure
      • Amazon Web Services
    • IDE & Tooling
      • BoxLang Debugger
        • MiniServer Debugging
        • CommandBox Debugging
      • BoxLang Compiler
      • CFML Feature Audit
      • CFML to BoxLang Transpiler
    • Runtime Configuration
      • Directives
      • Caches
      • Datasources
      • Experimental
      • Executors
      • Logging
      • Modules
      • Security
  • BoxLang Language
    • Program Structure
    • Syntax & Semantics
      • Comments
      • Variables
      • Variable Scopes
      • Operators
      • Null & Nothingness
      • Strings
      • Numbers
      • JSON
      • Arrays
      • Structures
      • Queries
      • Datasources
      • Conditionals
      • Attempts
      • Data Navigators
      • Exception Management
      • Code Locking
      • Closures => Context Aware
      • Lambdas -> Pure Functions
      • Includes
      • Threading
    • Classes & O.O.
      • Properties
      • Functions
      • Static Constructs
      • Final Constructs
      • Abstract Constructs
      • Interfaces
    • Reference
      • API Docs
      • Lexical Elements
        • Scopes and Constants
        • Keywords
        • Operators
        • Literals
        • Comments
        • Tokens
        • Semicolons
        • Identifiers
        • Packages and Imports
        • Java Interoperability
        • Errors
      • Types
        • array
        • class
        • date
        • datetime
        • file
        • numeric
        • query
        • stream
        • string
        • struct
        • xml
      • Built-in Functions
        • array
          • ArrayAppend
          • ArrayAvg
          • ArrayClear
          • ArrayContains
          • ArrayContainsNoCase
          • ArrayDelete
          • ArrayDeleteAt
          • ArrayDeleteNoCase
          • ArrayEach
          • ArrayEvery
          • ArrayFilter
          • ArrayFind
          • ArrayFindAll
          • ArrayFindAllNoCase
          • ArrayFindNoCase
          • ArrayFirst
          • ArrayGetMetadata
          • ArrayIndexExists
          • ArrayInsertAt
          • ArrayIsDefined
          • ArrayLast
          • ArrayMap
          • ArrayMax
          • ArrayMedian
          • ArrayMerge
          • ArrayMid
          • ArrayMin
          • ArrayNew
          • ArrayPop
          • ArrayPrepend
          • ArrayPush
          • ArrayRange
          • ArrayReduce
          • ArrayReduceRight
          • ArrayResize
          • ArrayReverse
          • ArraySet
          • ArrayShift
          • ArraySlice
          • ArraySome
          • ArraySort
          • ArraySplice
          • ArraySum
          • ArraySwap
          • ArrayToList
          • ArrayToStruct
          • ArrayUnshift
        • async
          • ExecutorGet
          • ExecutorHas
          • ExecutorList
          • ExecutorNew
          • ExecutorShutdown
          • ExecutorStatus
          • FutureNew
          • IsInThread
          • RunAsync
          • ThreadJoin
          • ThreadNew
          • ThreadTerminate
        • bifs
          • BoxLangBIFProxy
        • binary
          • BinaryDecode
          • BinaryEncode
          • BitAnd
          • BitMaskClear
          • BitMaskRead
          • BitMaskSet
          • BitNot
          • BitOr
          • bitShln
          • bitShrn
          • BitXor
        • cache
          • Cache
          • CacheFilter
          • CacheNames
          • CacheProviders
          • CacheService
        • cli
          • CLIExit
          • CLIGetArgs
          • CLIRead
        • conversion
          • DataNavigate
          • JSONDeserialize
          • JSONPrettify
          • JSONSerialize
          • LSParseNumber
          • ParseNumber
          • ToBase64
          • ToBinary
          • ToModifiable
          • ToNumeric
          • ToScript
          • ToString
          • ToUnmodifiable
        • decision
          • ArrayIsEmpty
          • Attempt
          • IsArray
          • IsBinary
          • IsBoolean
          • IsClosure
          • IsCustomFunction
          • IsDate
          • IsDateObject
          • IsDebugMode
          • IsDefined
          • IsEmpty
          • IsFileObject
          • IsIPv6
          • IsJSON
          • IsLeapYear
          • IsLocalHost
          • IsNull
          • IsNumeric
          • IsNumericDate
          • IsObject
          • IsQuery
          • IsSimpleValue
          • IsStruct
          • IsValid
          • IsXML
          • IsXmlAttribute
          • IsXMLDoc
          • IsXMLElem
          • IsXMLNode
          • IsXMLRoot
          • LSIsNumeric
          • structIsEmpty
        • encryption
          • Decrypt
          • Encrypt
          • EncryptBinary
          • GeneratePDBKDFKey
          • GenerateSecretKey
          • Hash
          • Hash40
          • Hmac
        • format
          • BooleanFormat
          • DecimalFormat
          • LSNumberFormat
          • NumberFormat
        • i18n
          • ClearLocale
          • CurrencyFormat
          • GetLocale
          • GetLocaleDisplayName
          • GetLocaleInfo
          • IsCurrency
          • LSCurrencyFormat
          • LSIsCurrency
          • LSParseCurrency
          • ParseCurrency
          • SetLocale
        • io
          • ContractPath
          • CreateTempDirectory
          • CreateTempFile
          • DirectoryCopy
          • DirectoryCreate
          • DirectoryDelete
          • DirectoryExists
          • DirectoryList
          • DirectoryMove
          • DirectoryRename
          • ExpandPath
          • FileAppend
          • FileClose
          • FileCopy
          • FileDelete
          • FileExists
          • FileGetMimeType
          • FileInfo
          • FileIsEOF
          • FileMove
          • FileOpen
          • FileRead
          • FileReadBinary
          • FileReadLine
          • FileSeek
          • FileSetAccessMode
          • FileSetAttribute
          • FileSetLastModified
          • FileSkipBytes
          • FileWrite
          • FileWriteLine
          • GetCanonicalPath
          • GetDirectoryFromPath
          • GetFileInfo
          • getTempFile
        • java
          • CreateDynamicProxy
        • jdbc
          • IsInTransaction
          • IsWithinTransaction
          • PreserveSingleQuotes
          • QueryExecute
          • TransactionCommit
          • TransactionRollback
          • TransactionSetSavepoint
        • list
          • GetToken
          • ListAppend
          • ListAvg
          • ListChangeDelims
          • ListCompact
          • ListContains
          • ListContainsNoCase
          • ListDeleteAt
          • ListEach
          • ListEvery
          • ListFilter
          • ListFind
          • ListFindNoCase
          • ListFirst
          • ListGetAt
          • ListIndexExists
          • ListInsertAt
          • ListItemTrim
          • ListLast
          • ListLen
          • ListMap
          • ListPrepend
          • ListQualify
          • ListReduceRight
          • ListRemoveDuplicates
          • ListRest
          • ListSetAt
          • ListSome
          • ListSort
          • ListToArray
          • ListTrim
          • ListValueCount
          • ListValueCountNoCase
        • math
          • Abs
          • Acos
          • Asin
          • Atn
          • Ceiling
          • Cos
          • DecrementValue
          • Exp
          • Fix
          • Floor
          • FormatBaseN
          • IncrementValue
          • InputBaseN
          • Int
          • Log
          • Log10
          • Max
          • Min
          • Pi
          • PrecisionEvaluate
          • Rand
          • Randomize
          • RandRange
          • Round
          • Sgn
          • Sin
          • Sqr
          • Tan
        • query
          • QueryAddColumn
          • QueryAddRow
          • QueryAppend
          • QueryClear
          • QueryColumnArray
          • QueryColumnCount
          • QueryColumnData
          • QueryColumnExists
          • QueryColumnList
          • QueryCurrentRow
          • QueryDeleteColumn
          • QueryDeleteRow
          • QueryEach
          • QueryEvery
          • QueryFilter
          • QueryGetCell
          • QueryGetResult
          • QueryInsertAt
          • QueryKeyExists
          • QueryMap
          • QueryNew
          • QueryPrepend
          • QueryRecordCount
          • QueryReduce
          • QueryRegisterFunction
          • QueryReverse
          • QueryRowData
          • QueryRowSwap
          • QuerySetCell
          • QuerySetRow
          • QuerySlice
          • QuerySome
          • QuerySort
        • string
          • Ascii
          • CamelCase
          • Char
          • CharsetDecode
          • CharsetEncode
          • Compare
          • CompareNoCase
          • Find
          • FindNoCase
          • FindOneOf
          • Insert
          • JSStringFormat
          • KebabCase
          • LCase
          • Left
          • ListReduce
          • LJustify
          • LTrim
          • Mid
          • ParagraphFormat
          • PascalCase
          • QueryStringToStruct
          • ReEscape
          • ReFind
          • reFindNoCase
          • ReMatch
          • reMatchNoCase
          • RemoveChars
          • RepeatString
          • Replace
          • ReplaceList
          • ReplaceListNoCase
          • ReplaceNoCase
          • ReReplace
          • reReplaceNoCase
          • Reverse
          • Right
          • RJustify
          • RTrim
          • Slugify
          • SnakeCase
          • SpanExcluding
          • SpanIncluding
          • SQLPrettify
          • StringBind
          • StringEach
          • StringEvery
          • StringFilter
          • StringMap
          • StringReduce
          • StringReduceRight
          • StringSome
          • StringSort
          • StripCR
          • Trim
          • TrueFalseFormat
          • UCase
          • UCFirst
          • Val
          • Wrap
          • YesNoFormat
        • struct
          • StructAppend
          • StructClear
          • StructCopy
          • StructDelete
          • StructEach
          • StructEquals
          • StructEvery
          • StructFilter
          • StructFind
          • StructFindKey
          • StructFindValue
          • StructGet
          • StructGetMetadata
          • StructInsert
          • StructIsCaseSensitive
          • StructIsOrdered
          • StructKeyArray
          • StructKeyExists
          • StructKeyList
          • StructKeyTranslate
          • StructMap
          • StructNew
          • StructReduce
          • StructSome
          • StructSort
          • StructToQueryString
          • StructToSorted
          • StructUpdate
          • StructValueArray
        • system
          • ApplicationRestart
          • ApplicationStartTime
          • ApplicationStop
          • BoxAnnounce
          • BoxAnnounceAsync
          • BoxRegisterInterceptionPoints
          • BoxRegisterInterceptor
          • BoxRegisterRequestInterceptor
          • CallStackGet
          • CreateGUID
          • CreateObject
          • CreateUUID
          • DE
          • DebugBoxContexts
          • Dump
          • Duplicate
          • echo
          • EncodeForHTML
          • GetApplicationMetadata
          • GetBaseTagData
          • GetBaseTagList
          • GetBaseTemplatePath
          • GetBoxContext
          • GetBoxRuntime
          • GetBoxVersionInfo
          • GetClassMetadata
          • GetComponentList
          • GetContextRoot
          • GetCurrentTemplatePath
          • GetFileFromPath
          • GetFunctionCalledName
          • GetFunctionList
          • GetModuleInfo
          • GetModuleList
          • GetRequestClassLoader
          • GetSemver
          • GetSystemSetting
          • GetTempDirectory
          • GetTickCount
          • htmlEditFormat
          • IIF
          • Invoke
          • IsInstanceOf
          • JavaCast
          • ObjectDeserialize
          • ObjectSerialize
          • PagePoolClear
          • Print
          • Println
          • RunThreadInContext
          • SessionInvalidate
          • SessionRotate
          • SessionStartTime
          • Sleep
          • SystemCacheClear
          • SystemExecute
          • SystemOutput
          • Throw
          • Trace
          • URLDecode
          • URLEncodedFormat
          • writeDump
          • WriteLog
          • WriteOutput
        • temporal
          • ClearTimezone
          • CreateDate
          • CreateDateTime
          • CreateODBCDate
          • CreateODBCDateTime
          • CreateODBCTime
          • CreateTime
          • CreateTimeSpan
          • DateAdd
          • DateCompare
          • DateConvert
          • DateDiff
          • DateFormat
          • DatePart
          • DateTimeFormat
          • Day
          • DayOfWeek
          • DayOfWeekAsString
          • DayOfWeekShortAsString
          • DayOfYear
          • DaysInMonth
          • DaysInYear
          • FirstDayOfMonth
          • GetNumericDate
          • GetTime
          • GetTimezone
          • GetTimezoneInfo
          • Hour
          • Millisecond
          • Minute
          • Month
          • MonthAsString
          • MonthShortAsString
          • Nanosecond
          • Now
          • Offset
          • ParseDateTime
          • Quarter
          • Second
          • SetTimezone
          • TimeFormat
          • Week
          • Year
        • type
          • ArrayLen
          • GetMetaData
          • Len
          • NullValue
          • StringLen
          • StructCount
        • web
          • HtmlHead
          • GetHTTPTimeString
          • GetHTTPRequestData
          • HtmlFooter
          • SetEncoding
          • Forward
          • Location
          • GetPageContext
          • FileUpload
          • FileUploadAll
        • xml
          • XMLChildPos
          • XMLElemNew
          • XMLFormat
          • XMLGetNodeType
          • XMLNew
          • XMLParse
          • XMLSearch
          • XMLTransform
          • XMLValidate
        • zip
          • Compress
          • Extract
          • IsZipFile
      • Components
        • async
          • Thread
        • cache
          • Cache
        • debug
          • Stopwatch
          • Timer
        • io
          • Directory
          • File
        • jdbc
          • DBInfo
          • ProcParam
          • ProcResult
          • Query
          • QueryParam
          • StoredProc
          • Transaction
        • net
          • HTTP
          • HTTPParam
        • system
          • Abort
          • Application
          • Associate
          • Component
          • Dump
          • Execute
          • Exit
          • Flush
          • Include
          • Invoke
          • InvokeArgument
          • Lock
          • Log
          • Loop
          • Object
          • Output
          • Param
          • ProcessingDirective
          • SaveContent
          • Setting
          • Silent
          • Sleep
          • Throw
          • Trace
        • web
          • HtmlHead
          • HtmlFooter
          • Location
          • Cookie
          • Header
          • Content
        • xml
          • XML
        • zip
          • Zip
      • Exceptions
  • BoxLang Framework
    • Application.bx
    • Asynchronous Programming
    • File Handling
    • Interceptors
      • Core Interception Points
        • Application Events
        • Cache Service Events
        • Cache Provider Events
        • Cache Object Store Events
        • Datasource Service Events
        • Dump Events
        • Dynamic Object Events
        • Function Invocations
        • HTTP Events
        • Life-cycle Events
        • Logging Events
        • Module Events
        • Module Service Events
        • Object Marshalling Events
        • Query Invocations
        • Runtime Events
        • Request Context Events
        • Scheduler Events
        • Scheduler Service Events
        • Template Invocations
        • Transaction Events
      • Request Interception Points
    • HTTP/S Calls
    • Java Interop
    • JDBC Transactions
    • Modules
      • AI
      • Compat CFML
        • Reference
          • Types
            • array
            • datetime
            • numeric
            • string
            • struct
          • Built-in Functions
            • cache
              • CacheCount
              • CacheGetAsAttempt
              • CacheRegionRemove
              • CacheRemoveAll
              • CachePut
              • CacheRegionExists
              • CacheGetSession
              • CacheGetEngineProperties
              • CacheGet
              • CacheGetDefaultCacheName
              • CacheGetProperties
              • CacheSetProperties
              • CacheGetAllIds
              • CacheIdExists
              • cacheKeyExists
              • CacheRemove
              • cacheDelete
              • CacheGetAll
              • CacheGetMetadata
              • CacheGetOrFail
              • CacheClear
              • CacheRegionNew
            • conversion
              • JSONDeserialize
            • encryption
              • Hash
              • Hash40
            • format
              • HTMLCodeFormat
              • DollarFormat
            • struct
              • DeleteClientVariable
            • system
              • Throw
              • ObjectSave
              • GetFunctionData
              • GetComponentMetadata
              • GetVariable
              • GetTagData
              • GetClientVariablesList
              • GetContextRoot
              • ObjectLoad
              • SetVariable
            • temporal
              • LSWeek
              • LSDayOfWeek
              • LSIsDate
              • DateCompare
              • GetHTTPTimestring
              • LSDateTimeFormat
              • LSDateFormat
              • LSTimeFormat
              • DayOfWeekAsString
              • DayOfWeekShortAsString
              • MonthAsString
              • MonthShortAsString
              • ToLegacyDate
              • createDate
              • LSParseDateTime
              • DateTimeFormat
              • DateFormat
              • TimeFormat
            • type
              • GetMetaData
          • Components
            • net
              • HTTP
      • CSRF
      • ESAPI
      • Evaluating Code
      • FTP
      • Image Manipulation
      • INI Files
      • JDBC
      • Jython
      • Mail
      • Markdown
      • ORM
      • OSHI - Operating System + Hardware
      • Password Encryption
      • PDF
      • Redis
      • UI Forms
      • WDDX
      • Web Support
      • Yaml
  • Extra Credit
    • MVC
    • Dependency Injection
Powered by GitBook
LogoLogo

Social Media

  • X
  • FaceBook
  • LinkedIn
  • YouTube

Bug Tracking

  • Runtimes
  • IDE
  • Modules

Support

  • Professional
  • Community
  • Slack

Copyright & Register Trademark by Ortus Solutions, Corp

On this page
  • BIFs
  • Case Insensitive
  • Naming Requirements
  • Reserved Words
  • Flexible Typing
  • Types
  • Conversions
  • Outputting Variables (Interpolation)
  • Debugging Variables
  • Server Debugging Templates
  • Paraming Variables
  • Checking For Existence
  • Java Integration
  • Member Functions
  • Naming Coding Standards

Was this helpful?

Edit on GitHub
Export as PDF
  1. BoxLang Language
  2. Syntax & Semantics

Variables

name = "Amazing Programmer"

PreviousCommentsNextVariable Scopes

Last updated 9 months ago

Was this helpful?

In BoxLang, variables are just pointers to a piece of data. They can hold any value you like and even change their value or type at runtime since BoxLang is a dynamic language. In some languages, you need to specify the type of data you want your variable to hold at compile-time and it can never change. You do not need to assign one in BoxLang, as everything is dynamic and/or inferred. It infers types according to the initial value you assign to your variable.

a = "string" // string
b = now() // datetime
c = 123 // integer
d = 1.34 // float
d2 = 12312377324234234234 // BigDecimal
f = false // boolean
g = [] // array
h = { name : "luis", isActive : true } // struct

Please note that assignments are evaluated from right to left instead of traditional reading from left to right.

Why don't you open the BoxLang REPL: boxlang or go to and try some stuff out.

> hello = "world"
world

> a = 5
5

> b = 10 + a
15

> c = 15 + a + b
35

> b = c * a
175

> d = [ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]

> myStruct = { key = "hola", today = now(), id = createUUID() }
{
  id : "B634D0D9-A32F-4781-A9F519258ED4B73D",
  today : {ts '2024-08-10 19:43:01'},
  key : "hola"
}

> println( a + b + c )
215

BIFs

print() // print to the out stream
println() // print with a line break
now() // get today's date time
createUUID() // generate a unique id

Case Insensitive

BoxLang is a case-insensitive language as well. Meaning if you create a variable a and reference it as A they are the same. This can be a big gotcha for developers from languages like Java or JavaScript. However, as best practice, we would recommend ALWAYS using the same case as when you define the variable:

Don't do this

a = "Hola Luis";
println( A );

Do this

a = "Hola Luis";
println( a );

Naming Requirements

Most BoxLang variables have a few requirements imposed by the Virtual Machine (VM)

  • It must begin with a letter, underscore, or Unicode currency symbol.

  • It can contain letters, numbers, underscore characters, and Unicode currency symbols.

  • NO SPACES!

  • Not case-sensitive

Reserved Words

As with any programming language, there are specific names you can't use, and some you can use. Here are the rules:

  • The name of any of the internal BoxLang persistent scopes: form, session, cgi, client, url, application, function

    • Technically you can create the variable by long scoping (local.form), but it is confusing and error-prone. So please be careful.

  • Reserved Operators

    • AND

    • EQ

    • EQUAL

    • EQV

    • GE

    • GREATER

    • GT

    • GTE

    • IMP

    • IS

    • LE

    • LESS

    • LT

    • LTE

    • MOD

    • NEQ

    • NOT

    • OR

    • THAN

    • XOR

  • Reserved Keywords

    • ABSTRACT

    • ANY

    • ARRAY

    • AS

    • ASSERT

    • BOOLEAN

    • BREAK

    • CASE

    • CASTAS

    • CATCH

    • CLASS

    • CONTAIN

    • CONTAINS

    • CONTINUE

    • DEFAULT

    • DO

    • DOES

    • ELIF

    • ELSE

    • FALSE

    • FINAL

    • FINALLY

    • FOR

    • FUNCTION

    • IF

    • IMPORT

    • IN

    • INCLUDE

    • INSTANCEOF

    • INTERFACE

    • JAVA

    • MESSAGE

    • NEW

    • NULL

    • NUMERIC

    • PACKAGE

    • PARAM

    • PRIVATE

    • PROPERTY

    • PUBLIC

    • QUERY

    • REMOTE

    • REQUEST

    • REQUIRED

    • RETHROW

    • RETURN

    • SERVER

    • SETTING

    • STATIC

    • STRING

    • STRUCT

    • SWITCH --> Could possibly be a var name, but not a function/method name

    • THROW

    • TO

    • TRUE

    • TRY

    • TYPE

    • VARIABLES

    • VAR

    • WHEN

    • WHILE

Flexible Typing

You can also create a variable with one type and then switch it to another dynamically:

a = "hello"
hello
a = 123
123
a = now()
{ts '2024-08-10 19:51:24'}
a = [1,2,3]
[1,2,3]

As you can see, the last equality wins! In this case, a is now an array.

Types

BoxLang is a typeless language, but internal types always exist which can be inferred or declared. BoxLang will automatically cast so you can do flexible typing assignments when evaluating expressions. It does all the tedious and hard job for you. If we were to categorize BoxLang variables into categories, these would be:

Category
Description

Binary

Raw data from files such as images, pdfs, etc

Complex

A data container that represents more than one value: structures, arrays, queries, XML document objects, etc.

Objects

Complex constructs representing data and functional operations. BoxLang Classes or Java Objects.

Simple

One value and used directly in expressions. These include numbers, strings, floats, booleans, and date-time values.

BoxLang also includes many validation functions that are available to you to test for the type of variable you are working with. You can also use the getmetdata() function to get the metadata about the variable as well.

qData = query.getMetadata()
a = now()
writedump( a.getMetadata() )
  • isArray()

  • isBinary()

  • isBoolean()

  • isCustomFunction()

  • isClosure()

  • isDate()

  • isDateObject()

  • isFileObject()

  • isJSON()

  • isIPv6()

  • isLeapYear()

  • isNumeric()

  • isNumericDate()

  • isObject()

  • isLocalHost()

  • isNull()

  • isPDFFile()

  • isPDFObject()

  • isQuery()

  • isSimpleValue()

  • isStruct()

  • isValid( type, value )

  • isXML()

  • isXmlDoc()

  • isXMLElem()

  • isXMLNode()

  • ixXMLRoot()

Conversions

You can also convert variables from one type to another in BoxLang. Here are some functions that will assist you in conversions:

  • arrayToList()

  • binaryDecode()

  • binaryEncode()

  • charsetDecode()

  • charsetEncode()

  • deserializeJSON()

  • entityToQuery()

  • hash()

  • hmac()

  • HTMLParse()

  • lcase()

  • listToArray()

  • parseNumber()

  • serializeJSON()

  • toBase64()

  • toBinary()

  • toScript()

  • toString()

  • URLDecode()

  • URLEncode()

  • URLEncodedFormat()

  • val()

  • XMLFormat()

  • XMLParse()

  • XMLTransform()

Outputting Variables (Interpolation)

You can also output or evaluate variables by using the # operators and using the variable name. This is referred to as interpolation in some languages:

a = "Hola Luis"
writeoutput( "Welcome to BoxLang: #a#" )
// Echo is the same as writeOutput
echo( "Welcome" )

Also, note that using the # hashes for output on assignments can be redundant if you do NOT use string interpolation but just variable assignments.

Don't do this

a = "hello luis";
b = #a#;
or
b = "#a#";

Do this

a = "hello luis";
b = a;

Debugging Variables

BoxLang offers one of the most used functions/tags ever: <bx:dump>, writeDump() and <bx:abort>, abort;. These are used to dump all the contents of a variable into the browser, console, or even a file. You can then leverage the abort construct to abort the request and see the output of your dumped variables. This will work with both simple and complex variables. However, be very careful when using it with Nested ORM objects, as you can potentially dump your entire database and crash the server. Leverage the top argument to limit dumping.

writeDump( complex );abort;

<bx:dump var="#server#" abort=true>

writeDump( var=arrayOfORM, top=5 );abort;

Server Debugging Templates

BoxLang also allows you to turn on/off a debugging template that shows up at the bottom of requests when running in server mode. You can activate this debugging by logging in to the appropriate engine administrator and looking for the debugging section. Turn it on and debug like a champ.

Paraming Variables

BoxLang allows you to set default values for variables if you use a variable that doesn't exist. You can use the <bx:param> tag or the param construct:

<bx:param name="myVariable" default="luis">

or

param myVariable = "luis";

Checking For Existence

You can verify if variables exist in many different ways. The following section showcases how variables are stored in visibility and persistence scopes, all of which are structures or hash maps in Java terms. This means you can leverage structure operations to check for existence and much more. Below are several ways to verify variable existence:

  • isDefined() - Evaluates a string value to determine whether the variable

    named in it exists.

  • isNull() - Returns true if the specified object is null, else false.

  • structKeyExists( key, value ) - Verifies if the specified key variable exists in a structure.

// Notice the variable name is in quotes
if( isDefined( "myVariable" ) ){
    writeOutput( myVariable );
} else {
    writeOutput( "Not Defined!" );
}

// Notice that the variable is NOT in quotes
if( isNull( myVariable ) ){
    writeOutput( "Not Defined!" );
} else {
    writeOutput( myVariable );
}

// What is this variables scopes???
if( structKeyExists( variables, "myVariable" ) ){
    writeOutput( myVariable );
} else {
    writeOutput( "Not Defined!" );
}

Java Integration

As we have discussed, BoxLang is a dynamic language built on Java. Thus each variable internally is represented by a native Java data type: String, Int, Float, Array, Vector, HashMap, etc. This is important because each variable you create has member functions available to you that delegate or reflect its native Java class.

a = "hello";
writeOutput( a.getClass().getName() );

If you run the script above in the REPL tool, you will see the output as java.lang.String. Therefore, the variable is typed as a String and can call on any method that java.lang.String implements. You can try this for the many types in BoxLang, like structs, arrays, objects, etc.

Member Functions

Here are some examples:

// Function passing
var myArray = [];
ArrayAppend( myArray, "objec_new" );
ArraySort( myArray, "ASC" );

// Member Functions
myArray.append( "objec_new" );
myArray.sort( "ASC" );

// Java Functions + BoxLang Functions
var myProductObject = createObject( "java", "myJavaclass" );
myjavaList = myProductObject.getProductList();
myjavaList.add( "newProduct" ); // Java API

myjavaList.append( "newProduct" ); // CF API
myjavaList.sort( "ASC" );

// DSL Chaining
s="the";
s = s.listAppend("quick brown fox", " ")
     .listAppend("jumps over the lazy dog", " ")
     .ucase()
     .reverse();

Member functions for the following data types are supported:

  • Array

  • String

  • List

  • Struct

  • Date

  • Spreadsheet

  • XML

  • Query

  • Image

Naming Coding Standards

As you can see, we can create , , , , uses headless functions (BIFS) and more. There is no need for types or special assignments. The BoxLang engine will determine or infer it and use it accordingly, thus a dynamic language.

BoxLang leverages several headless built-in functions that are available anywhere you code. These will be referred to you as BIFs. You can see our to check them out. Here are some we used:

Please note that some of them can be used as member functions directly on a specific object type.

You can even assign types to parameterize variables and much more. Check out the docs for it:

Besides the native Java member functions available to you, BoxLang also allows you to call on each variable's data type functions and chain them to create friendly language DSLs. This way, you do not have to pass variables into functions but treat the variables as objects. You can see all the member functions available according to data type here:

Please see for further information on member functions.

At , we have developed a set of development standards for many languages. You can find our BoxLang standards here:

try.boxlang.io
strings
numerics
arrays
structs
reference guide
https://boxlang.ortusbooks.com/boxlang-language/reference/built-in-functions/conversion
https://boxlang.ortusbooks.com/boxlang-language/reference/components/system/param
https://boxlang.ortusbooks.com/getting-started/overview/syntax-style-guide#member-functions
https://boxlang.ortusbooks.com/getting-started/overview/syntax-style-guide#member-functions
Ortus Solutions
https://github.com/Ortus-Solutions/coding-standards