repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L843-L848
go
train
// ToUserData returns an interface{} of the userdata of the value at index. // Otherwise, it returns nil. // // http://www.lua.org/manual/5.2/manual.html#lua_touserdata
func (l *State) ToUserData(index int) interface{}
// ToUserData returns an interface{} of the userdata of the value at index. // Otherwise, it returns nil. // // http://www.lua.org/manual/5.2/manual.html#lua_touserdata func (l *State) ToUserData(index int) interface{}
{ if d, ok := l.indexToValue(index).(*userData); ok { return d.data } return nil }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L854-L859
go
train
// ToThread converts the value at index to a Lua thread (a State). This // value must be a thread, otherwise the return value will be nil. // // http://www.lua.org/manual/5.2/manual.html#lua_tothread
func (l *State) ToThread(index int) *State
// ToThread converts the value at index to a Lua thread (a State). This // value must be a thread, otherwise the return value will be nil. // // http://www.lua.org/manual/5.2/manual.html#lua_tothread func (l *State) ToThread(index int) *State
{ if t, ok := l.indexToValue(index).(*State); ok { return t } return nil }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L871-L881
go
train
// ToValue convertes the value at index into a generic Go interface{}. The // value can be a userdata, a table, a thread, a function, or Go string, bool // or float64 types. Otherwise, the function returns nil. // // Different objects will give different values. There is no way to convert // the value back into its original value. // // Typically, this function is used only for debug information. // // http://www.lua.org/manual/5.2/manual.html#lua_tovalue
func (l *State) ToValue(index int) interface{}
// ToValue convertes the value at index into a generic Go interface{}. The // value can be a userdata, a table, a thread, a function, or Go string, bool // or float64 types. Otherwise, the function returns nil. // // Different objects will give different values. There is no way to convert // the value back into its original value. // // Typically, this function is used only for debug information. // // http://www.lua.org/manual/5.2/manual.html#lua_tovalue func (l *State) ToValue(index int) interface{}
{ v := l.indexToValue(index) switch v := v.(type) { case string, float64, bool, *table, *luaClosure, *goClosure, *goFunction, *State: case *userData: return v.data default: return nil } return v }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L886-L889
go
train
// PushString pushes a string onto the stack. // // http://www.lua.org/manual/5.2/manual.html#lua_pushstring
func (l *State) PushString(s string) string
// PushString pushes a string onto the stack. // // http://www.lua.org/manual/5.2/manual.html#lua_pushstring func (l *State) PushString(s string) string
{ // TODO is it useful to return the argument? l.apiPush(s) return s }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L899-L942
go
train
// PushFString pushes onto the stack a formatted string and returns that // string. It is similar to fmt.Sprintf, but has some differences: the // conversion specifiers are quite restricted. There are no flags, widths, // or precisions. The conversion specifiers can only be %% (inserts a % // in the string), %s, %f (a Lua number), %p (a pointer as a hexadecimal // numeral), %d and %c (an integer as a byte). // // http://www.lua.org/manual/5.2/manual.html#lua_pushfstring
func (l *State) PushFString(format string, args ...interface{}) string
// PushFString pushes onto the stack a formatted string and returns that // string. It is similar to fmt.Sprintf, but has some differences: the // conversion specifiers are quite restricted. There are no flags, widths, // or precisions. The conversion specifiers can only be %% (inserts a % // in the string), %s, %f (a Lua number), %p (a pointer as a hexadecimal // numeral), %d and %c (an integer as a byte). // // http://www.lua.org/manual/5.2/manual.html#lua_pushfstring func (l *State) PushFString(format string, args ...interface{}) string
{ n, i := 0, 0 for { e := strings.IndexRune(format, '%') if e < 0 { break } l.checkStack(2) // format + item l.push(format[:e]) switch format[e+1] { case 's': if args[i] == nil { l.push("(null)") } else { l.push(args[i].(string)) } i++ case 'c': l.push(string(args[i].(rune))) i++ case 'd': l.push(float64(args[i].(int))) i++ case 'f': l.push(args[i].(float64)) i++ case 'p': l.push(fmt.Sprintf("%p", args[i])) i++ case '%': l.push("%") default: l.runtimeError("invalid option " + format[e:e+2] + " to 'lua_pushfstring'") } n += 2 format = format[e+2:] } l.checkStack(1) l.push(format) if n > 0 { l.concat(n + 1) } return l.stack[l.top-1].(string) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L959-L971
go
train
// PushGoClosure pushes a new Go closure onto the stack. // // When a Go function is created, it is possible to associate some values with // it, thus creating a Go closure; these values are then accessible to the // function whenever it is called. To associate values with a Go function, // first these values should be pushed onto the stack (when there are multiple // values, the first value is pushed first). Then PushGoClosure is called to // create and push the Go function onto the stack, with the argument upValueCount // telling how many values should be associated with the function. Calling // PushGoClosure also pops these values from the stack. // // When upValueCount is 0, this function creates a light Go function, which is just a // Go function. // // http://www.lua.org/manual/5.2/manual.html#lua_pushcclosure
func (l *State) PushGoClosure(function Function, upValueCount uint8)
// PushGoClosure pushes a new Go closure onto the stack. // // When a Go function is created, it is possible to associate some values with // it, thus creating a Go closure; these values are then accessible to the // function whenever it is called. To associate values with a Go function, // first these values should be pushed onto the stack (when there are multiple // values, the first value is pushed first). Then PushGoClosure is called to // create and push the Go function onto the stack, with the argument upValueCount // telling how many values should be associated with the function. Calling // PushGoClosure also pops these values from the stack. // // When upValueCount is 0, this function creates a light Go function, which is just a // Go function. // // http://www.lua.org/manual/5.2/manual.html#lua_pushcclosure func (l *State) PushGoClosure(function Function, upValueCount uint8)
{ if upValueCount == 0 { l.apiPush(&goFunction{function}) } else { n := int(upValueCount) l.checkElementCount(n) cl := &goClosure{function: function, upValues: make([]value, upValueCount)} l.top -= n copy(cl.upValues, l.stack[l.top:l.top+n]) l.apiPush(cl) } }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L977-L980
go
train
// PushThread pushes the thread l onto the stack. It returns true if l is // the main thread of its state. // // http://www.lua.org/manual/5.2/manual.html#lua_pushthread
func (l *State) PushThread() bool
// PushThread pushes the thread l onto the stack. It returns true if l is // the main thread of its state. // // http://www.lua.org/manual/5.2/manual.html#lua_pushthread func (l *State) PushThread() bool
{ l.apiPush(l) return l.global.mainThread == l }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L985-L989
go
train
// Global pushes onto the stack the value of the global name. // // http://www.lua.org/manual/5.2/manual.html#lua_getglobal
func (l *State) Global(name string)
// Global pushes onto the stack the value of the global name. // // http://www.lua.org/manual/5.2/manual.html#lua_getglobal func (l *State) Global(name string)
{ g := l.global.registry.atInt(RegistryIndexGlobals) l.push(name) l.stack[l.top-1] = l.tableAt(g, l.stack[l.top-1]) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L996-L1000
go
train
// Field pushes onto the stack the value table[name], where table is the // table on the stack at the given index. This call may trigger a // metamethod for the __index event. // // http://www.lua.org/manual/5.2/manual.html#lua_getfield
func (l *State) Field(index int, name string)
// Field pushes onto the stack the value table[name], where table is the // table on the stack at the given index. This call may trigger a // metamethod for the __index event. // // http://www.lua.org/manual/5.2/manual.html#lua_getfield func (l *State) Field(index int, name string)
{ t := l.indexToValue(index) l.apiPush(name) l.stack[l.top-1] = l.tableAt(t, l.stack[l.top-1]) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1005-L1008
go
train
// RawGet is similar to GetTable, but does a raw access (without metamethods). // // http://www.lua.org/manual/5.2/manual.html#lua_rawget
func (l *State) RawGet(index int)
// RawGet is similar to GetTable, but does a raw access (without metamethods). // // http://www.lua.org/manual/5.2/manual.html#lua_rawget func (l *State) RawGet(index int)
{ t := l.indexToValue(index).(*table) l.stack[l.top-1] = t.at(l.stack[l.top-1]) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1015-L1018
go
train
// RawGetInt pushes onto the stack the value table[key] where table is the // value at index on the stack. The access is raw, as it doesn't invoke // metamethods. // // http://www.lua.org/manual/5.2/manual.html#lua_rawgeti
func (l *State) RawGetInt(index, key int)
// RawGetInt pushes onto the stack the value table[key] where table is the // value at index on the stack. The access is raw, as it doesn't invoke // metamethods. // // http://www.lua.org/manual/5.2/manual.html#lua_rawgeti func (l *State) RawGetInt(index, key int)
{ t := l.indexToValue(index).(*table) l.apiPush(t.atInt(key)) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1025-L1028
go
train
// RawGetValue pushes onto the stack value table[p] where table is the // value at index on the stack, and p is a light userdata. The access is // raw, as it doesn't invoke metamethods. // // http://www.lua.org/manual/5.2/manual.html#lua_rawgetp
func (l *State) RawGetValue(index int, p interface{})
// RawGetValue pushes onto the stack value table[p] where table is the // value at index on the stack, and p is a light userdata. The access is // raw, as it doesn't invoke metamethods. // // http://www.lua.org/manual/5.2/manual.html#lua_rawgetp func (l *State) RawGetValue(index int, p interface{})
{ t := l.indexToValue(index).(*table) l.apiPush(t.at(p)) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1039-L1041
go
train
// CreateTable creates a new empty table and pushes it onto the stack. // arrayCount is a hint for how many elements the table will have as a // sequence; recordCount is a hint for how many other elements the table // will have. Lua may use these hints to preallocate memory for the the new // table. This pre-allocation is useful for performance when you know in // advance how many elements the table will have. Otherwise, you can use the // function NewTable. // // http://www.lua.org/manual/5.2/manual.html#lua_createtable
func (l *State) CreateTable(arrayCount, recordCount int)
// CreateTable creates a new empty table and pushes it onto the stack. // arrayCount is a hint for how many elements the table will have as a // sequence; recordCount is a hint for how many other elements the table // will have. Lua may use these hints to preallocate memory for the the new // table. This pre-allocation is useful for performance when you know in // advance how many elements the table will have. Otherwise, you can use the // function NewTable. // // http://www.lua.org/manual/5.2/manual.html#lua_createtable func (l *State) CreateTable(arrayCount, recordCount int)
{ l.apiPush(newTableWithSize(arrayCount, recordCount)) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1048-L1063
go
train
// MetaTable pushes onto the stack the metatable of the value at index. If // the value at index does not have a metatable, the function returns // false and nothing is put onto the stack. // // http://www.lua.org/manual/5.2/manual.html#lua_getmetatable
func (l *State) MetaTable(index int) bool
// MetaTable pushes onto the stack the metatable of the value at index. If // the value at index does not have a metatable, the function returns // false and nothing is put onto the stack. // // http://www.lua.org/manual/5.2/manual.html#lua_getmetatable func (l *State) MetaTable(index int) bool
{ var mt *table switch v := l.indexToValue(index).(type) { case *table: mt = v.metaTable case *userData: mt = v.metaTable default: mt = l.global.metaTable(v) } if mt == nil { return false } l.apiPush(mt) return true }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1069-L1076
go
train
// UserValue pushes onto the stack the Lua value associated with the userdata // at index. This value must be a table or nil. // // http://www.lua.org/manual/5.2/manual.html#lua_getuservalue
func (l *State) UserValue(index int)
// UserValue pushes onto the stack the Lua value associated with the userdata // at index. This value must be a table or nil. // // http://www.lua.org/manual/5.2/manual.html#lua_getuservalue func (l *State) UserValue(index int)
{ d := l.indexToValue(index).(*userData) if d.env == nil { l.apiPush(nil) } else { l.apiPush(d.env) } }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1082-L1088
go
train
// SetGlobal pops a value from the stack and sets it as the new value of // global name. // // http://www.lua.org/manual/5.2/manual.html#lua_setglobal
func (l *State) SetGlobal(name string)
// SetGlobal pops a value from the stack and sets it as the new value of // global name. // // http://www.lua.org/manual/5.2/manual.html#lua_setglobal func (l *State) SetGlobal(name string)
{ l.checkElementCount(1) g := l.global.registry.atInt(RegistryIndexGlobals) l.push(name) l.setTableAt(g, l.stack[l.top-1], l.stack[l.top-2]) l.top -= 2 // pop value and key }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1098-L1102
go
train
// SetTable does the equivalent of table[key]=v, where table is the value // at index, v is the value at the top of the stack and key is the value // just below the top. // // The function pops both the key and the value from the stack. As in Lua, // this function may trigger a metamethod for the __newindex event. // // http://www.lua.org/manual/5.2/manual.html#lua_settable
func (l *State) SetTable(index int)
// SetTable does the equivalent of table[key]=v, where table is the value // at index, v is the value at the top of the stack and key is the value // just below the top. // // The function pops both the key and the value from the stack. As in Lua, // this function may trigger a metamethod for the __newindex event. // // http://www.lua.org/manual/5.2/manual.html#lua_settable func (l *State) SetTable(index int)
{ l.checkElementCount(2) l.setTableAt(l.indexToValue(index), l.stack[l.top-2], l.stack[l.top-1]) l.top -= 2 }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1108-L1114
go
train
// RawSet is similar to SetTable, but does a raw assignment (without // metamethods). // // http://www.lua.org/manual/5.2/manual.html#lua_rawset
func (l *State) RawSet(index int)
// RawSet is similar to SetTable, but does a raw assignment (without // metamethods). // // http://www.lua.org/manual/5.2/manual.html#lua_rawset func (l *State) RawSet(index int)
{ l.checkElementCount(2) t := l.indexToValue(index).(*table) t.put(l, l.stack[l.top-2], l.stack[l.top-1]) t.invalidateTagMethodCache() l.top -= 2 }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1123-L1128
go
train
// RawSetInt does the equivalent of table[n]=v where table is the table at // index and v is the value at the top of the stack. // // This function pops the value from the stack. The assignment is raw; it // doesn't invoke metamethods. // // http://www.lua.org/manual/5.2/manual.html#lua_rawseti
func (l *State) RawSetInt(index, key int)
// RawSetInt does the equivalent of table[n]=v where table is the table at // index and v is the value at the top of the stack. // // This function pops the value from the stack. The assignment is raw; it // doesn't invoke metamethods. // // http://www.lua.org/manual/5.2/manual.html#lua_rawseti func (l *State) RawSetInt(index, key int)
{ l.checkElementCount(1) t := l.indexToValue(index).(*table) t.putAtInt(key, l.stack[l.top-1]) l.top-- }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1134-L1144
go
train
// SetUserValue pops a table or nil from the stack and sets it as the new // value associated to the userdata at index. // // http://www.lua.org/manual/5.2/manual.html#lua_setuservalue
func (l *State) SetUserValue(index int)
// SetUserValue pops a table or nil from the stack and sets it as the new // value associated to the userdata at index. // // http://www.lua.org/manual/5.2/manual.html#lua_setuservalue func (l *State) SetUserValue(index int)
{ l.checkElementCount(1) d := l.indexToValue(index).(*userData) if l.stack[l.top-1] == nil { d.env = nil } else { t := l.stack[l.top-1].(*table) d.env = t } l.top-- }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1150-L1165
go
train
// SetMetaTable pops a table from the stack and sets it as the new metatable // for the value at index. // // http://www.lua.org/manual/5.2/manual.html#lua_setmetatable
func (l *State) SetMetaTable(index int)
// SetMetaTable pops a table from the stack and sets it as the new metatable // for the value at index. // // http://www.lua.org/manual/5.2/manual.html#lua_setmetatable func (l *State) SetMetaTable(index int)
{ l.checkElementCount(1) mt, ok := l.stack[l.top-1].(*table) if apiCheck && !ok && l.stack[l.top-1] != nil { panic("table expected") } switch v := l.indexToValue(index).(type) { case *table: v.metaTable = mt case *userData: v.metaTable = mt default: l.global.metaTables[l.TypeOf(index)] = mt } l.top-- }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1191-L1200
go
train
// Next pops a key from the stack and pushes a key-value pair from the table // at index, while the table has next elements. If there are no more // elements, nothing is pushed on the stack and Next returns false. // // A typical traversal looks like this: // // // Table is on top of the stack (index -1). // l.PushNil() // Add nil entry on stack (need 2 free slots). // for l.Next(-2) { // key := lua.CheckString(l, -2) // val := lua.CheckString(l, -1) // l.Pop(1) // Remove val, but need key for the next iter. // } // // http://www.lua.org/manual/5.2/manual.html#lua_next
func (l *State) Next(index int) bool
// Next pops a key from the stack and pushes a key-value pair from the table // at index, while the table has next elements. If there are no more // elements, nothing is pushed on the stack and Next returns false. // // A typical traversal looks like this: // // // Table is on top of the stack (index -1). // l.PushNil() // Add nil entry on stack (need 2 free slots). // for l.Next(-2) { // key := lua.CheckString(l, -2) // val := lua.CheckString(l, -1) // l.Pop(1) // Remove val, but need key for the next iter. // } // // http://www.lua.org/manual/5.2/manual.html#lua_next func (l *State) Next(index int) bool
{ t := l.indexToValue(index).(*table) if l.next(t, l.top-1) { l.apiIncrementTop() return true } // no more elements l.top-- // remove key return false }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1209-L1216
go
train
// Concat concatenates the n values at the top of the stack, pops them, and // leaves the result at the top. If n is 1, the result is the single value // on the stack (that is, the function does nothing); if n is 0, the result // is the empty string. Concatenation is performed following the usual // semantic of Lua. // // http://www.lua.org/manual/5.2/manual.html#lua_concat
func (l *State) Concat(n int)
// Concat concatenates the n values at the top of the stack, pops them, and // leaves the result at the top. If n is 1, the result is the single value // on the stack (that is, the function does nothing); if n is 0, the result // is the empty string. Concatenation is performed following the usual // semantic of Lua. // // http://www.lua.org/manual/5.2/manual.html#lua_concat func (l *State) Concat(n int)
{ l.checkElementCount(n) if n >= 2 { l.concat(n) } else if n == 0 { // push empty string l.apiPush("") } // else n == 1; nothing to do }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1222-L1225
go
train
// Register sets the Go function f as the new value of global name. If // name was already defined, it is overwritten. // // http://www.lua.org/manual/5.2/manual.html#lua_register
func (l *State) Register(name string, f Function)
// Register sets the Go function f as the new value of global name. If // name was already defined, it is overwritten. // // http://www.lua.org/manual/5.2/manual.html#lua_register func (l *State) Register(name string, f Function)
{ l.PushGoFunction(f) l.SetGlobal(name) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1258-L1268
go
train
// UpValue returns the name of the upvalue at index away from function, // where index cannot be greater than the number of upvalues. // // Returns an empty string and false if the index is greater than the number // of upvalues.
func UpValue(l *State, function, index int) (name string, ok bool)
// UpValue returns the name of the upvalue at index away from function, // where index cannot be greater than the number of upvalues. // // Returns an empty string and false if the index is greater than the number // of upvalues. func UpValue(l *State, function, index int) (name string, ok bool)
{ if c, isClosure := l.indexToValue(function).(closure); isClosure { if ok = 1 <= index && index <= c.upValueCount(); ok { if c, isLua := c.(*luaClosure); isLua { name = c.prototype.upValues[index-1].name } l.apiPush(c.upValue(index - 1)) } } return }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1278-L1289
go
train
// SetUpValue sets the value of a closure's upvalue. It assigns the value at // the top of the stack to the upvalue and returns its name. It also pops a // value from the stack. function and index are as in UpValue. // // Returns an empty string and false if the index is greater than the number // of upvalues. // // http://www.lua.org/manual/5.2/manual.html#lua_setupvalue
func SetUpValue(l *State, function, index int) (name string, ok bool)
// SetUpValue sets the value of a closure's upvalue. It assigns the value at // the top of the stack to the upvalue and returns its name. It also pops a // value from the stack. function and index are as in UpValue. // // Returns an empty string and false if the index is greater than the number // of upvalues. // // http://www.lua.org/manual/5.2/manual.html#lua_setupvalue func SetUpValue(l *State, function, index int) (name string, ok bool)
{ if c, isClosure := l.indexToValue(function).(closure); isClosure { if ok = 1 <= index && index <= c.upValueCount(); ok { if c, isLua := c.(*luaClosure); isLua { name = c.prototype.upValues[index-1].name } l.top-- c.setUpValue(index-1, l.stack[l.top]) } } return }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1303-L1311
go
train
// UpValueId returns a unique identifier for the upvalue numbered n from the // closure at index f. Parameters f and n are as in UpValue (but n cannot be // greater than the number of upvalues). // // These unique identifiers allow a program to check whether different // closures share upvalues. Lua closures that share an upvalue (that is, that // access a same external local variable) will return identical ids for those // upvalue indices.
func UpValueId(l *State, f, n int) interface{}
// UpValueId returns a unique identifier for the upvalue numbered n from the // closure at index f. Parameters f and n are as in UpValue (but n cannot be // greater than the number of upvalues). // // These unique identifiers allow a program to check whether different // closures share upvalues. Lua closures that share an upvalue (that is, that // access a same external local variable) will return identical ids for those // upvalue indices. func UpValueId(l *State, f, n int) interface{}
{ switch fun := l.indexToValue(f).(type) { case *luaClosure: return *l.upValue(f, n) case *goClosure: return &fun.upValues[n-1] } panic("closure expected") }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1315-L1319
go
train
// UpValueJoin makes the n1-th upvalue of the Lua closure at index f1 refer to // the n2-th upvalue of the Lua closure at index f2.
func UpValueJoin(l *State, f1, n1, f2, n2 int)
// UpValueJoin makes the n1-th upvalue of the Lua closure at index f1 refer to // the n2-th upvalue of the Lua closure at index f2. func UpValueJoin(l *State, f1, n1, f2, n2 int)
{ u1 := l.upValue(f1, n1) u2 := l.upValue(f2, n2) *u1 = *u2 }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1358-L1360
go
train
// Call calls a function. To do so, use the following protocol: first, the // function to be called is pushed onto the stack; then, the arguments to the // function are pushed in direct order - that is, the first argument is pushed // first. Finally, call Call. argCount is the number of arguments that you // pushed onto the stack. All arguments and the function value are popped // from the stack when the function is called. // // The results are pushed onto the stack when the function returns. The // number of results is adjusted to resultCount, unless resultCount is // MultipleReturns. In this case, all results from the function are pushed. // Lua takes care that the returned values fit into the stack space. The // function results are pushed onto the stack in direct order (the first // result is pushed first), so that after the call the last result is on the // top of the stack. // // Any error inside the called function provokes a call to panic(). // // The following example shows how the host program can do the equivalent to // this Lua code: // // a = f("how", t.x, 14) // // Here it is in Go: // // l.Global("f") // Function to be called. // l.PushString("how") // 1st argument. // l.Global("t") // Table to be indexed. // l.Field(-1, "x") // Push result of t.x (2nd arg). // l.Remove(-2) // Remove t from the stack. // l.PushInteger(14) // 3rd argument. // l.Call(3, 1) // Call f with 3 arguments and 1 result. // l.SetGlobal("a") // Set global a. // // Note that the code above is "balanced": at its end, the stack is back to // its original configuration. This is considered good programming practice. // // http://www.lua.org/manual/5.2/manual.html#lua_call
func (l *State) Call(argCount, resultCount int)
// Call calls a function. To do so, use the following protocol: first, the // function to be called is pushed onto the stack; then, the arguments to the // function are pushed in direct order - that is, the first argument is pushed // first. Finally, call Call. argCount is the number of arguments that you // pushed onto the stack. All arguments and the function value are popped // from the stack when the function is called. // // The results are pushed onto the stack when the function returns. The // number of results is adjusted to resultCount, unless resultCount is // MultipleReturns. In this case, all results from the function are pushed. // Lua takes care that the returned values fit into the stack space. The // function results are pushed onto the stack in direct order (the first // result is pushed first), so that after the call the last result is on the // top of the stack. // // Any error inside the called function provokes a call to panic(). // // The following example shows how the host program can do the equivalent to // this Lua code: // // a = f("how", t.x, 14) // // Here it is in Go: // // l.Global("f") // Function to be called. // l.PushString("how") // 1st argument. // l.Global("t") // Table to be indexed. // l.Field(-1, "x") // Push result of t.x (2nd arg). // l.Remove(-2) // Remove t from the stack. // l.PushInteger(14) // 3rd argument. // l.Call(3, 1) // Call f with 3 arguments and 1 result. // l.SetGlobal("a") // Set global a. // // Note that the code above is "balanced": at its end, the stack is back to // its original configuration. This is considered good programming practice. // // http://www.lua.org/manual/5.2/manual.html#lua_call func (l *State) Call(argCount, resultCount int)
{ l.CallWithContinuation(argCount, resultCount, 0, nil) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
lua.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1420-L1422
go
train
// Table pushes onto the stack the value table[top], where table is the // value at index, and top is the value at the top of the stack. This // function pops the key from the stack, putting the resulting value in its // place. As in Lua, this function may trigger a metamethod for the __index // event. // // http://www.lua.org/manual/5.2/manual.html#lua_gettable
func (l *State) Table(index int)
// Table pushes onto the stack the value table[top], where table is the // value at index, and top is the value at the top of the stack. This // function pops the key from the stack, putting the resulting value in its // place. As in Lua, this function may trigger a metamethod for the __index // event. // // http://www.lua.org/manual/5.2/manual.html#lua_gettable func (l *State) Table(index int)
{ l.stack[l.top-1] = l.tableAt(l.indexToValue(index), l.stack[l.top-1]) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
math.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/math.go#L112-L119
go
train
// MathOpen opens the math library. Usually passed to Require.
func MathOpen(l *State) int
// MathOpen opens the math library. Usually passed to Require. func MathOpen(l *State) int
{ NewLibrary(l, mathLibrary) l.PushNumber(3.1415926535897932384626433832795) // TODO use math.Pi instead? Values differ. l.SetField(-2, "pi") l.PushNumber(math.MaxFloat64) l.SetField(-2, "huge") return 1 }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
libs.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/libs.go#L31-L54
go
train
// OpenLibraries opens all standard libraries. Alternatively, the host program // can open them individually by using Require to call BaseOpen (for the basic // library), PackageOpen (for the package library), CoroutineOpen (for the // coroutine library), StringOpen (for the string library), TableOpen (for the // table library), MathOpen (for the mathematical library), Bit32Open (for the // bit library), IOOpen (for the I/O library), OSOpen (for the Operating System // library), and DebugOpen (for the debug library). // // The standard Lua libraries provide useful functions that are implemented // directly through the Go API. Some of these functions provide essential // services to the language (e.g. Type and MetaTable); others provide access // to "outside" services (e.g. I/O); and others could be implemented in Lua // itself, but are quite useful or have critical performance requirements that // deserve an implementation in Go (e.g. table.sort). // // All libraries are implemented through the official Go API. Currently, Lua // has the following standard libraries: // basic library // package library // string manipulation // table manipulation // mathematical functions (sin, log, etc.); // bitwise operations // input and output // operating system facilities // debug facilities // Except for the basic and the package libraries, each library provides all // its functions as fields of a global table or as methods of its objects.
func OpenLibraries(l *State, preloaded ...RegistryFunction)
// OpenLibraries opens all standard libraries. Alternatively, the host program // can open them individually by using Require to call BaseOpen (for the basic // library), PackageOpen (for the package library), CoroutineOpen (for the // coroutine library), StringOpen (for the string library), TableOpen (for the // table library), MathOpen (for the mathematical library), Bit32Open (for the // bit library), IOOpen (for the I/O library), OSOpen (for the Operating System // library), and DebugOpen (for the debug library). // // The standard Lua libraries provide useful functions that are implemented // directly through the Go API. Some of these functions provide essential // services to the language (e.g. Type and MetaTable); others provide access // to "outside" services (e.g. I/O); and others could be implemented in Lua // itself, but are quite useful or have critical performance requirements that // deserve an implementation in Go (e.g. table.sort). // // All libraries are implemented through the official Go API. Currently, Lua // has the following standard libraries: // basic library // package library // string manipulation // table manipulation // mathematical functions (sin, log, etc.); // bitwise operations // input and output // operating system facilities // debug facilities // Except for the basic and the package libraries, each library provides all // its functions as fields of a global table or as methods of its objects. func OpenLibraries(l *State, preloaded ...RegistryFunction)
{ libs := []RegistryFunction{ {"_G", BaseOpen}, {"package", PackageOpen}, // {"coroutine", CoroutineOpen}, {"table", TableOpen}, {"io", IOOpen}, {"os", OSOpen}, {"string", StringOpen}, {"bit32", Bit32Open}, {"math", MathOpen}, {"debug", DebugOpen}, } for _, lib := range libs { Require(l, lib.Name, lib.Function, true) l.Pop(1) } SubTable(l, RegistryIndex, "_PRELOAD") for _, lib := range preloaded { l.PushGoFunction(lib.Function) l.SetField(-2, lib.Name) } l.Pop(1) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
io.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/io.go#L310-L324
go
train
// IOOpen opens the io library. Usually passed to Require.
func IOOpen(l *State) int
// IOOpen opens the io library. Usually passed to Require. func IOOpen(l *State) int
{ NewLibrary(l, ioLibrary) NewMetaTable(l, fileHandle) l.PushValue(-1) l.SetField(-2, "__index") SetFunctions(l, fileHandleMethods, 0) l.Pop(1) registerStdFile(l, os.Stdin, input, "stdin") registerStdFile(l, os.Stdout, output, "stdout") registerStdFile(l, os.Stderr, "", "stderr") return 1 }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L48-L77
go
train
// Traceback creates and pushes a traceback of the stack l1. If message is not // nil it is appended at the beginning of the traceback. The level parameter // tells at which level to start the traceback.
func Traceback(l, l1 *State, message string, level int)
// Traceback creates and pushes a traceback of the stack l1. If message is not // nil it is appended at the beginning of the traceback. The level parameter // tells at which level to start the traceback. func Traceback(l, l1 *State, message string, level int)
{ const levels1, levels2 = 12, 10 levels := countLevels(l1) mark := 0 if levels > levels1+levels2 { mark = levels1 } buf := message if buf != "" { buf += "\n" } buf += "stack traceback:" for f, ok := Stack(l1, level); ok; f, ok = Stack(l1, level) { if level++; level == mark { buf += "\n\t..." level = levels - levels2 } else { d, _ := Info(l1, "Slnt", f) buf += "\n\t" + d.ShortSource + ":" if d.CurrentLine > 0 { buf += fmt.Sprintf("%d:", d.CurrentLine) } buf += " in " + functionName(l, d) if d.IsTailCall { buf += "\n\t(...tail calls...)" } } } l.PushString(buf) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L82-L94
go
train
// MetaField pushes onto the stack the field event from the metatable of the // object at index. If the object does not have a metatable, or if the // metatable does not have this field, returns false and pushes nothing.
func MetaField(l *State, index int, event string) bool
// MetaField pushes onto the stack the field event from the metatable of the // object at index. If the object does not have a metatable, or if the // metatable does not have this field, returns false and pushes nothing. func MetaField(l *State, index int, event string) bool
{ if !l.MetaTable(index) { return false } l.PushString(event) l.RawGet(-2) if l.IsNil(-1) { l.Pop(2) // remove metatable and metafield return false } l.Remove(-2) // remove only metatable return true }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L103-L111
go
train
// CallMeta calls a metamethod. // // If the object at index has a metatable and this metatable has a field event, // this function calls this field passing the object as its only argument. In // this case this function returns true and pushes onto the stack the value // returned by the call. If there is no metatable or no metamethod, this // function returns false (without pushing any value on the stack).
func CallMeta(l *State, index int, event string) bool
// CallMeta calls a metamethod. // // If the object at index has a metatable and this metatable has a field event, // this function calls this field passing the object as its only argument. In // this case this function returns true and pushes onto the stack the value // returned by the call. If there is no metatable or no metamethod, this // function returns false (without pushing any value on the stack). func CallMeta(l *State, index int, event string) bool
{ index = l.AbsIndex(index) if !MetaField(l, index, event) { return false } l.PushValue(index) l.Call(1, 1) return true }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L118-L140
go
train
// ArgumentError raises an error with a standard message that includes extraMessage as a comment. // // This function never returns. It is an idiom to use it in Go functions as // lua.ArgumentError(l, args, "message") // panic("unreachable")
func ArgumentError(l *State, argCount int, extraMessage string)
// ArgumentError raises an error with a standard message that includes extraMessage as a comment. // // This function never returns. It is an idiom to use it in Go functions as // lua.ArgumentError(l, args, "message") // panic("unreachable") func ArgumentError(l *State, argCount int, extraMessage string)
{ f, ok := Stack(l, 0) if !ok { // no stack frame? Errorf(l, "bad argument #%d (%s)", argCount, extraMessage) return } d, _ := Info(l, "n", f) if d.NameKind == "method" { argCount-- // do not count 'self' if argCount == 0 { // error is in the self argument itself? Errorf(l, "calling '%s' on bad self (%s)", d.Name, extraMessage) return } } if d.Name == "" { if pushGlobalFunctionName(l, f) { d.Name, _ = l.ToString(-1) } else { d.Name = "?" } } Errorf(l, "bad argument #%d to '%s' (%s)", argCount, d.Name, extraMessage) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L190-L199
go
train
// Where pushes onto the stack a string identifying the current position of // the control at level in the call stack. Typically this string has the // following format: // chunkname:currentline: // Level 0 is the running function, level 1 is the function that called the // running function, etc. // // This function is used to build a prefix for error messages.
func Where(l *State, level int)
// Where pushes onto the stack a string identifying the current position of // the control at level in the call stack. Typically this string has the // following format: // chunkname:currentline: // Level 0 is the running function, level 1 is the function that called the // running function, etc. // // This function is used to build a prefix for error messages. func Where(l *State, level int)
{ if f, ok := Stack(l, level); ok { // check function at level ar, _ := Info(l, "Sl", f) // get info about it if ar.CurrentLine > 0 { // is there info? l.PushString(fmt.Sprintf("%s:%d: ", ar.ShortSource, ar.CurrentLine)) return } } l.PushString("") // else, no information available... }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L209-L214
go
train
// Errorf raises an error. The error message format is given by format plus // any extra arguments, following the same rules as PushFString. It also adds // at the beginning of the message the file name and the line number where // the error occurred, if this information is available. // // This function never returns. It is an idiom to use it in Go functions as: // lua.Errorf(l, args) // panic("unreachable")
func Errorf(l *State, format string, a ...interface{})
// Errorf raises an error. The error message format is given by format plus // any extra arguments, following the same rules as PushFString. It also adds // at the beginning of the message the file name and the line number where // the error occurred, if this information is available. // // This function never returns. It is an idiom to use it in Go functions as: // lua.Errorf(l, args) // panic("unreachable") func Errorf(l *State, format string, a ...interface{})
{ Where(l, 1) l.PushFString(format, a...) l.Concat(2) l.Error() }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L223-L241
go
train
// ToStringMeta converts any Lua value at the given index to a Go string in a // reasonable format. The resulting string is pushed onto the stack and also // returned by the function. // // If the value has a metatable with a "__tostring" field, then ToStringMeta // calls the corresponding metamethod with the value as argument, and uses // the result of the call as its result.
func ToStringMeta(l *State, index int) (string, bool)
// ToStringMeta converts any Lua value at the given index to a Go string in a // reasonable format. The resulting string is pushed onto the stack and also // returned by the function. // // If the value has a metatable with a "__tostring" field, then ToStringMeta // calls the corresponding metamethod with the value as argument, and uses // the result of the call as its result. func ToStringMeta(l *State, index int) (string, bool)
{ if !CallMeta(l, index, "__tostring") { switch l.TypeOf(index) { case TypeNumber, TypeString: l.PushValue(index) case TypeBoolean: if l.ToBoolean(index) { l.PushString("true") } else { l.PushString("false") } case TypeNil: l.PushString("nil") default: l.PushFString("%s: %p", TypeNameOf(l, index), l.ToValue(index)) } } return l.ToString(-1) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L249-L258
go
train
// NewMetaTable returns false if the registry already has the key name. Otherwise, // creates a new table to be used as a metatable for userdata, adds it to the // registry with key name, and returns true. // // In both cases it pushes onto the stack the final value associated with name in // the registry.
func NewMetaTable(l *State, name string) bool
// NewMetaTable returns false if the registry already has the key name. Otherwise, // creates a new table to be used as a metatable for userdata, adds it to the // registry with key name, and returns true. // // In both cases it pushes onto the stack the final value associated with name in // the registry. func NewMetaTable(l *State, name string) bool
{ if MetaTableNamed(l, name); !l.IsNil(-1) { return false } l.Pop(1) l.NewTable() l.PushValue(-1) l.SetField(RegistryIndex, name) return true }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L285-L291
go
train
// CheckUserData checks whether the function argument at index is a userdata // of the type name (see NewMetaTable) and returns the userdata (see // ToUserData).
func CheckUserData(l *State, index int, name string) interface{}
// CheckUserData checks whether the function argument at index is a userdata // of the type name (see NewMetaTable) and returns the userdata (see // ToUserData). func CheckUserData(l *State, index int, name string) interface{}
{ if d := TestUserData(l, index, name); d != nil { return d } typeError(l, index, name) panic("unreachable") }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L294-L298
go
train
// CheckType checks whether the function argument at index has type t. See Type for the encoding of types for t.
func CheckType(l *State, index int, t Type)
// CheckType checks whether the function argument at index has type t. See Type for the encoding of types for t. func CheckType(l *State, index int, t Type)
{ if l.TypeOf(index) != t { tagError(l, index, t) } }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L301-L305
go
train
// CheckAny checks whether the function has an argument of any type (including nil) at position index.
func CheckAny(l *State, index int)
// CheckAny checks whether the function has an argument of any type (including nil) at position index. func CheckAny(l *State, index int)
{ if l.TypeOf(index) == TypeNone { ArgumentError(l, index, "value expected") } }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L308-L312
go
train
// ArgumentCheck checks whether cond is true. If not, raises an error with a standard message.
func ArgumentCheck(l *State, cond bool, index int, extraMessage string)
// ArgumentCheck checks whether cond is true. If not, raises an error with a standard message. func ArgumentCheck(l *State, cond bool, index int, extraMessage string)
{ if !cond { ArgumentError(l, index, extraMessage) } }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L317-L323
go
train
// CheckString checks whether the function argument at index is a string and returns this string. // // This function uses ToString to get its result, so all conversions and caveats of that function apply here.
func CheckString(l *State, index int) string
// CheckString checks whether the function argument at index is a string and returns this string. // // This function uses ToString to get its result, so all conversions and caveats of that function apply here. func CheckString(l *State, index int) string
{ if s, ok := l.ToString(index); ok { return s } tagError(l, index, TypeString) panic("unreachable") }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L327-L332
go
train
// OptString returns the string at index if it is a string. If this argument is // absent or is nil, returns def. Otherwise, raises an error.
func OptString(l *State, index int, def string) string
// OptString returns the string at index if it is a string. If this argument is // absent or is nil, returns def. Otherwise, raises an error. func OptString(l *State, index int, def string) string
{ if l.IsNoneOrNil(index) { return def } return CheckString(l, index) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L441-L453
go
train
// Require calls function f with string name as an argument and sets the call // result in package.loaded[name], as if that function had been called // through require. // // If global is true, also stores the result into global name. // // Leaves a copy of that result on the stack.
func Require(l *State, name string, f Function, global bool)
// Require calls function f with string name as an argument and sets the call // result in package.loaded[name], as if that function had been called // through require. // // If global is true, also stores the result into global name. // // Leaves a copy of that result on the stack. func Require(l *State, name string, f Function, global bool)
{ l.PushGoFunction(f) l.PushString(name) // argument to f l.Call(1, 1) // open module SubTable(l, RegistryIndex, "_LOADED") l.PushValue(-2) // make copy of module (call result) l.SetField(-2, name) // _LOADED[name] = module l.Pop(1) // remove _LOADED table if global { l.PushValue(-1) // copy of module l.SetGlobal(name) // _G[name] = module } }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L536-L546
go
train
// NewStateEx creates a new Lua state. It calls NewState and then sets a panic // function that prints an error message to the standard error output in case // of fatal errors. // // Returns the new state.
func NewStateEx() *State
// NewStateEx creates a new Lua state. It calls NewState and then sets a panic // function that prints an error message to the standard error output in case // of fatal errors. // // Returns the new state. func NewStateEx() *State
{ l := NewState() if l != nil { _ = AtPanic(l, func(l *State) int { s, _ := l.ToString(-1) fmt.Fprintf(os.Stderr, "PANIC: unprotected error in call to Lua API (%s)\n", s) return 0 }) } return l }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L560-L573
go
train
// FileResult produces the return values for file-related functions in the standard // library (io.open, os.rename, file:seek, etc.).
func FileResult(l *State, err error, filename string) int
// FileResult produces the return values for file-related functions in the standard // library (io.open, os.rename, file:seek, etc.). func FileResult(l *State, err error, filename string) int
{ if err == nil { l.PushBoolean(true) return 1 } l.PushNil() if filename != "" { l.PushString(filename + ": " + err.Error()) } else { l.PushString(err.Error()) } l.PushInteger(0) // TODO map err to errno return 3 }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L576-L581
go
train
// DoFile loads and runs the given file.
func DoFile(l *State, fileName string) error
// DoFile loads and runs the given file. func DoFile(l *State, fileName string) error
{ if err := LoadFile(l, fileName, ""); err != nil { return err } return l.ProtectedCall(0, MultipleReturns, 0) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
auxiliary.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L584-L589
go
train
// DoString loads and runs the given string.
func DoString(l *State, s string) error
// DoString loads and runs the given string. func DoString(l *State, s string) error
{ if err := LoadString(l, s); err != nil { return err } return l.ProtectedCall(0, MultipleReturns, 0) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
stack.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/stack.go#L371-L387
go
train
// Call a Go or Lua function. The function to be called is at function. // The arguments are on the stack, right after the function. On return, all the // results are on the stack, starting at the original function position.
func (l *State) call(function int, resultCount int, allowYield bool)
// Call a Go or Lua function. The function to be called is at function. // The arguments are on the stack, right after the function. On return, all the // results are on the stack, starting at the original function position. func (l *State) call(function int, resultCount int, allowYield bool)
{ if l.nestedGoCallCount++; l.nestedGoCallCount == maxCallCount { l.runtimeError("Go stack overflow") } else if l.nestedGoCallCount >= maxCallCount+maxCallCount>>3 { l.throw(ErrorError) // error while handling stack error } if !allowYield { l.nonYieldableCallCount++ } if !l.preCall(function, resultCount) { // is a Lua function? l.execute() // call it } if !allowYield { l.nonYieldableCallCount-- } l.nestedGoCallCount-- }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
load.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/load.go#L152-L191
go
train
// PackageOpen opens the package library. Usually passed to Require.
func PackageOpen(l *State) int
// PackageOpen opens the package library. Usually passed to Require. func PackageOpen(l *State) int
{ NewLibrary(l, packageLibrary) createSearchersTable(l) l.SetField(-2, "searchers") setPath(l, "path", "LUA_PATH", defaultPath) l.PushString(fmt.Sprintf("%c\n%c\n?\n!\n-\n", filepath.Separator, pathListSeparator)) l.SetField(-2, "config") SubTable(l, RegistryIndex, "_LOADED") l.SetField(-2, "loaded") SubTable(l, RegistryIndex, "_PRELOAD") l.SetField(-2, "preload") l.PushGlobalTable() l.PushValue(-2) SetFunctions(l, []RegistryFunction{{"require", func(l *State) int { name := CheckString(l, 1) l.SetTop(1) l.Field(RegistryIndex, "_LOADED") l.Field(2, name) if l.ToBoolean(-1) { return 1 } l.Pop(1) findLoader(l, name) l.PushString(name) l.Insert(-2) l.Call(2, 1) if !l.IsNil(-1) { l.SetField(2, name) } l.Field(2, name) if l.IsNil(-1) { l.PushBoolean(true) l.PushValue(-1) l.SetField(2, name) } return 1 }}}, 1) l.Pop(1) return 1 }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
base.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/base.go#L322-L330
go
train
// BaseOpen opens the basic library. Usually passed to Require.
func BaseOpen(l *State) int
// BaseOpen opens the basic library. Usually passed to Require. func BaseOpen(l *State) int
{ l.PushGlobalTable() l.PushGlobalTable() l.SetField(-2, "_G") SetFunctions(l, baseLibrary, 0) l.PushString(VersionString) l.SetField(-2, "_VERSION") return 1 }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
types.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/types.go#L209-L218
go
train
// Converts an integer to a "floating point byte", represented as // (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if // eeeee != 0 and (xxx) otherwise.
func float8FromInt(x int) float8
// Converts an integer to a "floating point byte", represented as // (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if // eeeee != 0 and (xxx) otherwise. func float8FromInt(x int) float8
{ if x < 8 { return float8(x) } e := 0 for ; x >= 0x10; e++ { x = (x + 1) >> 1 } return float8(((e + 1) << 3) | (x - 8)) }
Shopify/go-lua
48449c60c0a91cdc83cf554aa0931380393b9b02
tables.go
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/tables.go#L148-L173
go
train
// OPT: tryPut is an optimized variant of the at/put pair used by setTableAt to avoid hashing the key twice.
func (t *table) tryPut(l *State, k, v value) bool
// OPT: tryPut is an optimized variant of the at/put pair used by setTableAt to avoid hashing the key twice. func (t *table) tryPut(l *State, k, v value) bool
{ switch k := k.(type) { case nil: case float64: if i := int(k); float64(i) == k && 0 < i && i <= len(t.array) && t.array[i-1] != nil { t.array[i-1] = v return true } else if math.IsNaN(k) { return false } else if t.hash[k] != nil && v != nil { t.hash[k] = v return true } case string: if t.hash[k] != nil && v != nil { t.hash[k] = v return true } default: if t.hash[k] != nil && v != nil { t.hash[k] = v return true } } return false }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/logs/logs.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/logs/logs.go#L53-L60
go
train
// Initialize.
func init()
// Initialize. func init()
{ root.Register(Command) f := Command.Flags() f.DurationVarP(&duration, "since", "s", 5*time.Minute, "Start time of the search") f.StringVarP(&filter, "filter", "F", "", "Filter logs with pattern") f.BoolVarP(&follow, "follow", "f", false, "Follow tails logs for updates") }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/logs/logs.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/logs/logs.go#L63-L89
go
train
// Run command.
func run(c *cobra.Command, args []string) error
// Run command. func run(c *cobra.Command, args []string) error
{ if err := root.Project.LoadFunctions(args...); err != nil { return err } config := logs.Config{ Service: cloudwatchlogs.New(root.Session), StartTime: time.Now().Add(-duration).UTC(), PollInterval: 5 * time.Second, Follow: follow, FilterPattern: filter, } l := &logs.Logs{ Config: config, } for _, fn := range root.Project.Functions { l.GroupNames = append(l.GroupNames, fn.GroupName()) } for event := range l.Start() { fmt.Printf("\033[34m%s\033[0m %s", event.GroupName, event.Message) } return l.Err() }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
logs/log.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/logs/log.go#L22-L26
go
train
// Start consuming logs.
func (l *Log) Start() <-chan *Event
// Start consuming logs. func (l *Log) Start() <-chan *Event
{ ch := make(chan *Event) go l.start(ch) return ch }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
logs/log.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/logs/log.go#L29-L58
go
train
// start consuming and exit after pagination if Follow is not enabled.
func (l *Log) start(ch chan<- *Event)
// start consuming and exit after pagination if Follow is not enabled. func (l *Log) start(ch chan<- *Event)
{ defer close(ch) l.Log.Debug("enter") defer l.Log.Debug("exit") var start = l.StartTime.UnixNano() / int64(time.Millisecond) var nextToken *string var err error for { l.Log.WithField("start", start).Debug("request") nextToken, start, err = l.fetch(nextToken, start, ch) if err != nil { l.err = fmt.Errorf("log %q: %s", l.GroupName, err) break } if nextToken == nil && l.Follow { time.Sleep(l.PollInterval) l.Log.WithField("start", start).Debug("poll") continue } if nextToken == nil { break } } }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
logs/log.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/logs/log.go#L61-L89
go
train
// fetch logs relative to the given token and start time. We ignore when the log group is not found.
func (l *Log) fetch(nextToken *string, start int64, ch chan<- *Event) (*string, int64, error)
// fetch logs relative to the given token and start time. We ignore when the log group is not found. func (l *Log) fetch(nextToken *string, start int64, ch chan<- *Event) (*string, int64, error)
{ res, err := l.Service.FilterLogEvents(&cloudwatchlogs.FilterLogEventsInput{ LogGroupName: &l.GroupName, FilterPattern: &l.FilterPattern, StartTime: &start, NextToken: nextToken, }) if e, ok := err.(awserr.Error); ok { if e.Code() == "ResourceNotFoundException" { l.Log.Debug("not found") return nil, 0, nil } } if err != nil { return nil, 0, err } for _, event := range res.Events { start = *event.Timestamp + 1 ch <- &Event{ GroupName: l.GroupName, Message: *event.Message, } } return res.NextToken, start, nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
plugins/golang/golang.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/golang/golang.go#L23-L45
go
train
// Open adds the shim and golang defaults.
func (p *Plugin) Open(fn *function.Function) error
// Open adds the shim and golang defaults. func (p *Plugin) Open(fn *function.Function) error
{ if !strings.HasPrefix(fn.Runtime, "go") { return nil } if fn.Runtime == "golang" { fn.Runtime = Runtime } if fn.Hooks.Build == "" { fn.Hooks.Build = "GOOS=linux GOARCH=amd64 go build -o main *.go" } if fn.Handler == "" { fn.Handler = "main" } if fn.Hooks.Clean == "" { fn.Hooks.Clean = "rm -f main" } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L122-L153
go
train
// Open the function.json file and prime the config.
func (f *Function) Open(environment string) error
// Open the function.json file and prime the config. func (f *Function) Open(environment string) error
{ f.defaults() f.Log = f.Log.WithFields(log.Fields{ "function": f.Name, "env": environment, }) f.Log.Debug("open") if err := f.loadConfig(environment); err != nil { return errors.Wrap(err, "loading config") } if err := f.hookOpen(); err != nil { return errors.Wrap(err, "open hook") } if err := validator.Validate(&f.Config); err != nil { return errors.Wrap(err, "validating") } ignoreFile, err := utils.ReadIgnoreFile(f.Path) if err != nil { return errors.Wrap(err, "reading ignore file") } f.IgnoreFile = append(f.IgnoreFile, []byte("\n")...) f.IgnoreFile = append(f.IgnoreFile, ignoreFile...) return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L156-L179
go
train
// defaults applies configuration defaults.
func (f *Function) defaults()
// defaults applies configuration defaults. func (f *Function) defaults()
{ if f.Alias == "" { f.Alias = CurrentAlias } if f.Plugins == nil { f.Plugins = defaultPlugins } if f.Environment == nil { f.Environment = make(map[string]string) } if f.VPC.Subnets == nil { f.VPC.Subnets = []string{} } if f.VPC.SecurityGroups == nil { f.VPC.SecurityGroups = []string{} } f.Setenv("APEX_FUNCTION_NAME", f.Name) f.Setenv("LAMBDA_FUNCTION_NAME", f.FunctionName) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L183-L207
go
train
// loadConfig for `environment`, attempt function.ENV.js first, then // fall back on function.json if it is available.
func (f *Function) loadConfig(environment string) error
// loadConfig for `environment`, attempt function.ENV.js first, then // fall back on function.json if it is available. func (f *Function) loadConfig(environment string) error
{ path := fmt.Sprintf("function.%s.json", environment) ok, err := f.tryConfig(path) if err != nil { return err } if ok { f.Log.WithField("config", path).Debug("loaded config") return nil } ok, err = f.tryConfig("function.json") if err != nil { return err } if ok { f.Log.WithField("config", "function.json").Debug("loaded config") return nil } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L210-L225
go
train
// tryConfig
func (f *Function) tryConfig(path string) (bool, error)
// tryConfig func (f *Function) tryConfig(path string) (bool, error)
{ file, err := os.Open(filepath.Join(f.Path, path)) if os.IsNotExist(err) { return false, nil } if err != nil { return false, err } if err := json.NewDecoder(file).Decode(&f.Config); err != nil { return false, err } return true, nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L228-L230
go
train
// Setenv sets environment variable `name` to `value`.
func (f *Function) Setenv(name, value string)
// Setenv sets environment variable `name` to `value`. func (f *Function) Setenv(name, value string)
{ f.Environment[name] = value }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L235-L266
go
train
// Deploy generates a zip and creates or deploy the function. // If the configuration hasn't been changed it will deploy only code, // otherwise it will deploy both configuration and code.
func (f *Function) Deploy() error
// Deploy generates a zip and creates or deploy the function. // If the configuration hasn't been changed it will deploy only code, // otherwise it will deploy both configuration and code. func (f *Function) Deploy() error
{ f.Log.Debug("deploying") zip, err := f.ZipBytes() if err != nil { return err } if err := f.hookDeploy(); err != nil { return err } config, err := f.GetConfig() if e, ok := err.(awserr.Error); ok { if e.Code() == "ResourceNotFoundException" { return f.Create(zip) } } if err != nil { return err } if f.configChanged(config) { f.Log.Debug("config changed") return f.DeployConfigAndCode(zip) } f.Log.Info("config unchanged") return f.DeployCode(zip, config) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L269-L298
go
train
// DeployCode deploys function code when changed.
func (f *Function) DeployCode(zip []byte, config *lambda.GetFunctionOutput) error
// DeployCode deploys function code when changed. func (f *Function) DeployCode(zip []byte, config *lambda.GetFunctionOutput) error
{ remoteHash := *config.Configuration.CodeSha256 localHash := utils.Sha256(zip) if localHash == remoteHash { f.Log.Info("code unchanged") version := config.Configuration.Version // Creating an alias to $LATEST would mean its tied to any future deploys. // To correct this behaviour, we take the latest version at the time of deploy. if *version == "$LATEST" { versions, err := f.versions() if err != nil { return err } version = versions[len(versions)-1].Version } return f.CreateOrUpdateAlias(f.Alias, *version) } f.Log.WithFields(log.Fields{ "local": localHash, "remote": remoteHash, }).Debug("code changed") return f.Update(zip) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L301-L332
go
train
// DeployConfigAndCode updates config and updates function code.
func (f *Function) DeployConfigAndCode(zip []byte) error
// DeployConfigAndCode updates config and updates function code. func (f *Function) DeployConfigAndCode(zip []byte) error
{ f.Log.Info("updating config") params := &lambda.UpdateFunctionConfigurationInput{ FunctionName: &f.FunctionName, MemorySize: &f.Memory, Timeout: &f.Timeout, Description: &f.Description, Role: &f.Role, Runtime: &f.Runtime, Handler: &f.Handler, KMSKeyArn: &f.KMSKeyArn, Environment: f.environment(), VpcConfig: &lambda.VpcConfig{ SecurityGroupIds: aws.StringSlice(f.VPC.SecurityGroups), SubnetIds: aws.StringSlice(f.VPC.Subnets), }, } if f.DeadLetterARN != "" { params.DeadLetterConfig = &lambda.DeadLetterConfig{ TargetArn: &f.DeadLetterARN, } } _, err := f.Service.UpdateFunctionConfiguration(params) if err != nil { return err } return f.Update(zip) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L335-L348
go
train
// Delete the function including all its versions
func (f *Function) Delete() error
// Delete the function including all its versions func (f *Function) Delete() error
{ f.Log.Info("deleting") _, err := f.Service.DeleteFunction(&lambda.DeleteFunctionInput{ FunctionName: &f.FunctionName, }) if err != nil { return err } f.Log.Info("function deleted") return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L351-L356
go
train
// GetConfig returns the function configuration.
func (f *Function) GetConfig() (*lambda.GetFunctionOutput, error)
// GetConfig returns the function configuration. func (f *Function) GetConfig() (*lambda.GetFunctionOutput, error)
{ f.Log.Debug("fetching config") return f.Service.GetFunction(&lambda.GetFunctionInput{ FunctionName: &f.FunctionName, }) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L359-L365
go
train
// GetConfigQualifier returns the function configuration for the given qualifier.
func (f *Function) GetConfigQualifier(s string) (*lambda.GetFunctionOutput, error)
// GetConfigQualifier returns the function configuration for the given qualifier. func (f *Function) GetConfigQualifier(s string) (*lambda.GetFunctionOutput, error)
{ f.Log.Debug("fetching config") return f.Service.GetFunction(&lambda.GetFunctionInput{ FunctionName: &f.FunctionName, Qualifier: &s, }) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L368-L370
go
train
// GetConfigCurrent returns the function configuration for the current version.
func (f *Function) GetConfigCurrent() (*lambda.GetFunctionOutput, error)
// GetConfigCurrent returns the function configuration for the current version. func (f *Function) GetConfigCurrent() (*lambda.GetFunctionOutput, error)
{ return f.GetConfigQualifier(f.Alias) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L373-L396
go
train
// Update the function with the given `zip`.
func (f *Function) Update(zip []byte) error
// Update the function with the given `zip`. func (f *Function) Update(zip []byte) error
{ f.Log.Info("updating function") updated, err := f.Service.UpdateFunctionCode(&lambda.UpdateFunctionCodeInput{ FunctionName: &f.FunctionName, Publish: aws.Bool(true), ZipFile: zip, }) if err != nil { return err } if err := f.CreateOrUpdateAlias(f.Alias, *updated.Version); err != nil { return err } f.Log.WithFields(log.Fields{ "version": *updated.Version, "name": f.FunctionName, }).Info("function updated") return f.cleanup() }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L399-L443
go
train
// Create the function with the given `zip`.
func (f *Function) Create(zip []byte) error
// Create the function with the given `zip`. func (f *Function) Create(zip []byte) error
{ f.Log.Info("creating function") params := &lambda.CreateFunctionInput{ FunctionName: &f.FunctionName, Description: &f.Description, MemorySize: &f.Memory, Timeout: &f.Timeout, Runtime: &f.Runtime, Handler: &f.Handler, Role: &f.Role, KMSKeyArn: &f.KMSKeyArn, Publish: aws.Bool(true), Environment: f.environment(), Code: &lambda.FunctionCode{ ZipFile: zip, }, VpcConfig: &lambda.VpcConfig{ SecurityGroupIds: aws.StringSlice(f.VPC.SecurityGroups), SubnetIds: aws.StringSlice(f.VPC.Subnets), }, } if f.DeadLetterARN != "" { params.DeadLetterConfig = &lambda.DeadLetterConfig{ TargetArn: &f.DeadLetterARN, } } created, err := f.Service.CreateFunction(params) if err != nil { return err } if err := f.CreateOrUpdateAlias(f.Alias, *created.Version); err != nil { return err } f.Log.WithFields(log.Fields{ "version": *created.Version, "name": f.FunctionName, }).Info("function created") return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L446-L474
go
train
// CreateOrUpdateAlias attempts creating the alias, or updates if it already exists.
func (f *Function) CreateOrUpdateAlias(alias, version string) error
// CreateOrUpdateAlias attempts creating the alias, or updates if it already exists. func (f *Function) CreateOrUpdateAlias(alias, version string) error
{ _, err := f.Service.CreateAlias(&lambda.CreateAliasInput{ FunctionName: &f.FunctionName, FunctionVersion: &version, Name: &alias, }) if err == nil { f.Log.WithField("version", version).Infof("created alias %s", alias) return nil } if e, ok := err.(awserr.Error); !ok || e.Code() != "ResourceConflictException" { return err } _, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, FunctionVersion: &version, Name: &alias, }) if err != nil { return err } f.Log.WithField("version", version).Infof("updated alias %s", alias) return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L477-L482
go
train
// GetAliases fetches a list of aliases for the function.
func (f *Function) GetAliases() (*lambda.ListAliasesOutput, error)
// GetAliases fetches a list of aliases for the function. func (f *Function) GetAliases() (*lambda.ListAliasesOutput, error)
{ f.Log.Debug("fetching aliases") return f.Service.ListAliases(&lambda.ListAliasesInput{ FunctionName: &f.FunctionName, }) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L485-L525
go
train
// Invoke the remote Lambda function, returning the response and logs, if any.
func (f *Function) Invoke(event, context interface{}) (reply, logs io.Reader, err error)
// Invoke the remote Lambda function, returning the response and logs, if any. func (f *Function) Invoke(event, context interface{}) (reply, logs io.Reader, err error)
{ eventBytes, err := json.Marshal(event) if err != nil { return nil, nil, err } contextBytes, err := json.Marshal(context) if err != nil { return nil, nil, err } res, err := f.Service.Invoke(&lambda.InvokeInput{ ClientContext: aws.String(base64.StdEncoding.EncodeToString(contextBytes)), FunctionName: &f.FunctionName, InvocationType: aws.String(string(RequestResponse)), LogType: aws.String("Tail"), Qualifier: &f.Alias, Payload: eventBytes, }) if err != nil { return nil, nil, err } logs = base64.NewDecoder(base64.StdEncoding, strings.NewReader(*res.LogResult)) if res.FunctionError != nil { e := &InvokeError{ Handled: *res.FunctionError == "Handled", } if err := json.Unmarshal(res.Payload, e); err != nil { return nil, logs, err } return nil, logs, e } reply = bytes.NewReader(res.Payload) return reply, logs, nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L528-L570
go
train
// Rollback the function to the previous.
func (f *Function) Rollback() error
// Rollback the function to the previous. func (f *Function) Rollback() error
{ f.Log.Info("rolling back") alias, err := f.currentVersionAlias() if err != nil { return err } f.Log.Debugf("current version: %s", *alias.FunctionVersion) versions, err := f.versions() if err != nil { return err } if len(versions) < 2 { return errors.New("Can't rollback. Only one version deployed.") } latest := *versions[len(versions)-1].Version prev := *versions[len(versions)-2].Version rollback := latest if *alias.FunctionVersion == latest { rollback = prev } f.Log.Infof("rollback to version: %s", rollback) _, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, FunctionVersion: &rollback, }) if err != nil { return err } f.Log.WithField("current version", rollback).Info("function rolled back") return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L573-L602
go
train
// RollbackVersion the function to the specified version.
func (f *Function) RollbackVersion(version string) error
// RollbackVersion the function to the specified version. func (f *Function) RollbackVersion(version string) error
{ f.Log.Info("rolling back") alias, err := f.currentVersionAlias() if err != nil { return err } f.Log.Debugf("current version: %s", *alias.FunctionVersion) if version == *alias.FunctionVersion { return errors.New("Specified version currently deployed.") } f.Log.Infof("rollback to version: %s", version) _, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, FunctionVersion: &version, }) if err != nil { return err } f.Log.WithField("current version", version).Info("function rolled back") return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L606-L614
go
train
// ZipBytes builds the in-memory zip, or reads // the .Zip from disk if specified.
func (f *Function) ZipBytes() ([]byte, error)
// ZipBytes builds the in-memory zip, or reads // the .Zip from disk if specified. func (f *Function) ZipBytes() ([]byte, error)
{ if f.Zip == "" { f.Log.Debug("building zip") return f.BuildBytes() } f.Log.Debugf("reading zip %q", f.Zip) return ioutil.ReadFile(f.Zip) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L617-L630
go
train
// BuildBytes returns the generated zip as bytes.
func (f *Function) BuildBytes() ([]byte, error)
// BuildBytes returns the generated zip as bytes. func (f *Function) BuildBytes() ([]byte, error)
{ r, err := f.Build() if err != nil { return nil, err } b, err := ioutil.ReadAll(r) if err != nil { return nil, err } f.Log.Debugf("created build (%s)", humanize.Bytes(uint64(len(b)))) return b, nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L633-L689
go
train
// Build returns the zipped contents of the function.
func (f *Function) Build() (io.Reader, error)
// Build returns the zipped contents of the function. func (f *Function) Build() (io.Reader, error)
{ f.Log.Debugf("creating build") buf := new(bytes.Buffer) zip := archive.NewZip(buf) if err := f.hookBuild(zip); err != nil { return nil, err } paths, err := utils.LoadFiles(f.Path, f.IgnoreFile) if err != nil { return nil, err } for _, path := range paths { f.Log.WithField("file", path).Debug("add file to zip") fullPath := filepath.Join(f.Path, path) fh, err := os.Open(fullPath) if err != nil { return nil, err } info, err := fh.Stat() if err != nil { return nil, err } if info.IsDir() { // It's a symlink, otherwise it shouldn't be returned by LoadFiles linkPath, err := filepath.EvalSymlinks(fullPath) if err != nil { return nil, err } if err := zip.AddDir(linkPath, path); err != nil { return nil, err } } else { if err := zip.AddFile(path, fh); err != nil { return nil, err } } if err := fh.Close(); err != nil { return nil, err } } if err := zip.Close(); err != nil { return nil, err } return buf, nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L702-L716
go
train
// Return function version from alias name, if alias not found, return the input
func (f *Function) GetVersionFromAlias(alias string) (string, error)
// Return function version from alias name, if alias not found, return the input func (f *Function) GetVersionFromAlias(alias string) (string, error)
{ var version string = alias aliases, err := f.GetAliases() if err != nil { return version, err } for _, fnAlias := range aliases.Aliases { if strings.Compare(version, *fnAlias.Name) == 0 { version = *fnAlias.FunctionVersion break } } return version, nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L719-L726
go
train
// cleanup removes any deployed functions beyond the configured `RetainedVersions` value
func (f *Function) cleanup() error
// cleanup removes any deployed functions beyond the configured `RetainedVersions` value func (f *Function) cleanup() error
{ versionsToCleanup, err := f.versionsToCleanup() if err != nil { return err } return f.removeVersions(versionsToCleanup) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L729-L753
go
train
// versions returns list of all versions deployed to AWS Lambda
func (f *Function) versions() ([]*lambda.FunctionConfiguration, error)
// versions returns list of all versions deployed to AWS Lambda func (f *Function) versions() ([]*lambda.FunctionConfiguration, error)
{ var list []*lambda.FunctionConfiguration request := lambda.ListVersionsByFunctionInput{ FunctionName: &f.FunctionName, } for { page, err := f.Service.ListVersionsByFunction(&request) if err != nil { return nil, err } list = append(list, page.Versions...) if page.NextMarker == nil { break } request.Marker = page.NextMarker } versions := list[1:] // remove $LATEST return versions, nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L756-L771
go
train
// versionsToCleanup returns list of versions to remove after updating function
func (f *Function) versionsToCleanup() ([]*lambda.FunctionConfiguration, error)
// versionsToCleanup returns list of versions to remove after updating function func (f *Function) versionsToCleanup() ([]*lambda.FunctionConfiguration, error)
{ versions, err := f.versions() if err != nil { return nil, err } if *f.RetainedVersions == 0 { return versions, nil } if len(versions) > *f.RetainedVersions { return versions[:len(versions)-*f.RetainedVersions], nil } return nil, nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L774-L789
go
train
// removeVersions removes specifed function's versions
func (f *Function) removeVersions(versions []*lambda.FunctionConfiguration) error
// removeVersions removes specifed function's versions func (f *Function) removeVersions(versions []*lambda.FunctionConfiguration) error
{ for _, v := range versions { f.Log.Debugf("cleaning up version: %s", *v.Version) _, err := f.Service.DeleteFunction(&lambda.DeleteFunctionInput{ FunctionName: &f.FunctionName, Qualifier: v.Version, }) if err != nil { return err } } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L792-L797
go
train
// currentVersionAlias returns alias configuration for currently deployed function
func (f *Function) currentVersionAlias() (*lambda.AliasConfiguration, error)
// currentVersionAlias returns alias configuration for currently deployed function func (f *Function) currentVersionAlias() (*lambda.AliasConfiguration, error)
{ return f.Service.GetAlias(&lambda.GetAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, }) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L800-L876
go
train
// configChanged checks if function configuration differs from configuration stored in AWS Lambda
func (f *Function) configChanged(config *lambda.GetFunctionOutput) bool
// configChanged checks if function configuration differs from configuration stored in AWS Lambda func (f *Function) configChanged(config *lambda.GetFunctionOutput) bool
{ type diffConfig struct { Description string Memory int64 Timeout int64 Role string Runtime string Handler string VPC vpc.VPC Environment []string KMSKeyArn string DeadLetterConfig lambda.DeadLetterConfig } localConfig := &diffConfig{ Description: f.Description, Memory: f.Memory, Timeout: f.Timeout, Role: f.Role, Runtime: f.Runtime, Handler: f.Handler, KMSKeyArn: f.KMSKeyArn, Environment: environ(f.environment().Variables), VPC: vpc.VPC{ Subnets: f.VPC.Subnets, SecurityGroups: f.VPC.SecurityGroups, }, } if f.DeadLetterARN != "" { localConfig.DeadLetterConfig = lambda.DeadLetterConfig{ TargetArn: &f.DeadLetterARN, } } remoteConfig := &diffConfig{ Description: *config.Configuration.Description, Memory: *config.Configuration.MemorySize, Timeout: *config.Configuration.Timeout, Role: *config.Configuration.Role, Runtime: *config.Configuration.Runtime, Handler: *config.Configuration.Handler, } if config.Configuration.KMSKeyArn != nil { remoteConfig.KMSKeyArn = *config.Configuration.KMSKeyArn } if config.Configuration.Environment != nil { remoteConfig.Environment = environ(config.Configuration.Environment.Variables) } if config.Configuration.DeadLetterConfig != nil { remoteConfig.DeadLetterConfig = lambda.DeadLetterConfig{ TargetArn: config.Configuration.DeadLetterConfig.TargetArn, } } // SDK is inconsistent here. VpcConfig can be nil or empty struct. remoteConfig.VPC = vpc.VPC{Subnets: []string{}, SecurityGroups: []string{}} if config.Configuration.VpcConfig != nil { remoteConfig.VPC = vpc.VPC{ Subnets: aws.StringValueSlice(config.Configuration.VpcConfig.SubnetIds), SecurityGroups: aws.StringValueSlice(config.Configuration.VpcConfig.SecurityGroupIds), } } // don't make any assumptions about the order AWS stores the subnets or security groups sort.StringSlice(remoteConfig.VPC.Subnets).Sort() sort.StringSlice(localConfig.VPC.Subnets).Sort() sort.StringSlice(remoteConfig.VPC.SecurityGroups).Sort() sort.StringSlice(localConfig.VPC.SecurityGroups).Sort() localConfigJSON, _ := json.Marshal(localConfig) remoteConfigJSON, _ := json.Marshal(remoteConfig) return string(localConfigJSON) != string(remoteConfigJSON) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L879-L888
go
train
// hookOpen calls Openers.
func (f *Function) hookOpen() error
// hookOpen calls Openers. func (f *Function) hookOpen() error
{ for _, name := range f.Plugins { if p, ok := plugins[name].(Opener); ok { if err := p.Open(f); err != nil { return err } } } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L891-L900
go
train
// hookBuild calls Builders.
func (f *Function) hookBuild(zip *archive.Zip) error
// hookBuild calls Builders. func (f *Function) hookBuild(zip *archive.Zip) error
{ for _, name := range f.Plugins { if p, ok := plugins[name].(Builder); ok { if err := p.Build(f, zip); err != nil { return err } } } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L903-L912
go
train
// hookClean calls Cleaners.
func (f *Function) hookClean() error
// hookClean calls Cleaners. func (f *Function) hookClean() error
{ for _, name := range f.Plugins { if p, ok := plugins[name].(Cleaner); ok { if err := p.Clean(f); err != nil { return err } } } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L915-L924
go
train
// hookDeploy calls Deployers.
func (f *Function) hookDeploy() error
// hookDeploy calls Deployers. func (f *Function) hookDeploy() error
{ for _, name := range f.Plugins { if p, ok := plugins[name].(Deployer); ok { if err := p.Deploy(f); err != nil { return err } } } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L927-L935
go
train
// environment for lambda calls.
func (f *Function) environment() *lambda.Environment
// environment for lambda calls. func (f *Function) environment() *lambda.Environment
{ env := make(map[string]*string) if !f.Edge { for k, v := range f.Environment { env[k] = aws.String(v) } } return &lambda.Environment{Variables: env} }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L938-L953
go
train
// environment sorted and joined.
func environ(env map[string]*string) []string
// environment sorted and joined. func environ(env map[string]*string) []string
{ var keys []string var pairs []string for k := range env { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { pairs = append(pairs, fmt.Sprintf("%s=%s", k, *env[k])) } return pairs }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
function/function.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L956-L966
go
train
// AWSConfig returns AWS configuration if function has specified region.
func (f *Function) AWSConfig() *aws.Config
// AWSConfig returns AWS configuration if function has specified region. func (f *Function) AWSConfig() *aws.Config
{ region := f.Config.Region if f.Config.Edge { region = "us-east-1" } if len(region) > 0 { return aws.NewConfig().WithRegion(region) } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/rollback/rollback.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/rollback/rollback.go#L39-L45
go
train
// Initialize.
func init()
// Initialize. func init()
{ root.Register(Command) f := Command.Flags() f.StringVarP(&alias, "alias", "a", "current", "Function alias") f.StringVarP(&version, "version", "v", "", "version to which rollback is done") }