Exemplo n.º 1
0
func main() {
	L := luar.Init()
	defer L.Close()

	L.GetGlobal("print")
	print := luar.NewLuaObject(L, -1)
	print.Call("one two", 12)

	L.GetGlobal("package")
	pack := luar.NewLuaObject(L, -1)
	fmt.Println(pack.Get("path"))

	/*
	   L.GetGlobal("string")
	   strtab := luar.NewLuaObject(L,-1)
	   iter := strtab.Iter()
	   for iter.Next() {
	       fmt.Println(iter.Key,iter.Value)
	   }
	*/

	gsub := luar.NewLuaObjectFromName(L, "string.gsub")
	res, err := gsub.Call("hello $NAME go $HOME", "%$(%u+)", luar.Map{
		"NAME": "Dolly",
		"HOME": "where you belong",
	})
	if res == nil {
		fmt.Println("error", err)
	} else {
		fmt.Println("result", res)
	}

}
Exemplo n.º 2
0
func main() {
	L := luar.Init()
	defer L.Close()

	L.GetGlobal("print")
	print := luar.NewLuaObject(L, -1)
	print.Call("one two", 12)

	L.GetGlobal("package")
	pack := luar.NewLuaObject(L, -1)
	fmt.Println(pack.Get("path"))

	lcopy := luar.NewLuaObjectFromValue

	gsub := luar.NewLuaObjectFromName(L, "string.gsub")

	rmap := lcopy(L, luar.Map{
		"NAME": "Dolly",
		"HOME": "where you belong",
	})

	res, err := gsub.Call("hello $NAME go $HOME", "%$(%u+)", rmap)
	if res == nil {
		fmt.Println("error", err)
	} else {
		fmt.Println("result", res)
	}

}
Exemplo n.º 3
0
func (PM *PluginManager) initLua() {
	PM.L = luar.Init()
	luar.RawRegister(PM.L, "", luar.Map{
		"RegisterCommand": func(L *lua.State) int {
			name := L.ToString(1)
			fn := luar.NewLuaObject(L, 2)
			PM.Commands[name] = Plugin{name, fn}
			log.Printf("    %-10s command\n", name)
			return 0
		},
		"RegisterEvent": func(L *lua.State) int {
			name := L.ToString(1)
			event := L.ToString(2)
			fn := luar.NewLuaObject(L, 3)
			if _, ok := PM.Events[event]; !ok {
				PM.Events[event] = make(map[string]Plugin)
			}
			PM.Events[event][name] = Plugin{name, fn}
			log.Printf("    %-10s event\n", name)
			return 0
		},
	})

	luar.Register(PM.L, "go", luar.Map{
		"Split":  strings.Split,
		"SplitN": strings.SplitN,
		"PrintTable": func(table interface{}) {
			log.Printf("%#v\n", table)
		},
	})
}
Exemplo n.º 4
0
func main() {
	whj := "wang::hai::jun"
	fmt.Println(strings.Split(whj, "::"))
	TestCall("111")
	L := luar.Init()
	defer L.Close()
	M := luar.Map{
		"one":   "ein",
		"two":   "zwei",
		"three": "drei",
	}

	S := []string{"alfred", "alice", "bob", "frodo"}

	ST := &MyStruct{"Dolly", 46}

	luar.Register(L, "", luar.Map{
		"Print":    fmt.Println,
		"testcall": TestCall,
		"print":    fmt.Println,
		"MSG":      "hello", // can also register constants
		"M":        M,
		"S":        S,
		"ST":       ST,
	})

	//L.DoString(test)
	L.DoString(code)
	L.GetGlobal("print")
	print := luar.NewLuaObject(L, -1)
	print.Call("one two", 12)

	L.GetGlobal("package")
	pack := luar.NewLuaObject(L, -1)
	fmt.Println(pack.Get("path"))

	lcopy := luar.NewLuaObjectFromValue

	gsub := luar.NewLuaObjectFromName(L, "string.gsub")

	rmap := lcopy(L, luar.Map{
		"NAME": "Dolly",
		"HOME": "where you belong",
	})

	res, err := gsub.Call("hello $NAME go $HOME", "%$(%u+)", rmap)
	if res == nil {
		fmt.Println("error", err)
	} else {
		fmt.Println("\033[0;31mresult\033[0m", res)
	}

}
Exemplo n.º 5
0
func (p *Plugin) apiProcessNew(l *lua.State) int {
	callback := luar.NewLuaObject(l, 1)
	command := l.ToString(2)

	args := make([]string, l.GetTop()-2)
	for i := 3; i <= l.GetTop(); i++ {
		args[i-3] = l.ToString(i)
	}

	proc := &process{
		cmd: exec.Command(command, args...),
	}

	go func() {
		var str string
		bytes, err := proc.cmd.Output()
		if err == nil {
			if bytes != nil {
				str = string(bytes)
			}
			p.callValue(callback, proc.cmd.ProcessState.Success(), str)
		} else {
			p.callValue(callback, false, "")
		}
		callback.Close()
	}()

	obj := luar.NewLuaObjectFromValue(l, proc)
	obj.Push()
	obj.Close()
	return 1
}
Exemplo n.º 6
0
func ExampleLuaTableIter_Next() {
	const code = `
return {
  foo = 17,
  bar = 18,
}
`

	L := luar.Init()
	defer L.Close()

	err := L.DoString(code)
	if err != nil {
		log.Fatal(err)
	}

	lo := luar.NewLuaObject(L, -1)

	iter := lo.Iter()
	keys := []string{}
	values := map[string]float64{}
	for iter.Next() {
		k := iter.Key.(string)
		keys = append(keys, k)
		values[k] = iter.Value.(float64)
	}
	sort.Strings(keys)

	for _, v := range keys {
		fmt.Println(v, values[v])
	}
	// Output:
	// bar 18
	// foo 17
}
Exemplo n.º 7
0
func (p *Plugin) apiAudioPlay(l *lua.State) int {
	if p.instance.Audio.IsPlaying() {
		l.PushBoolean(false)
		return 1
	}

	obj := luar.NewLuaObject(l, 1)
	filename := obj.Get("filename").(string)
	callback := obj.GetObject("callback")
	obj.Close()

	if enc, ok := p.instance.Client.AudioEncoder.(*opus.Encoder); ok {
		enc.SetApplication(gopus.Audio)
	}

	p.instance.Audio.Source = gumble_ffmpeg.SourceFile(filename)
	p.instance.Audio.Play()
	go func() {
		p.instance.Audio.Wait()
		if callback.Type != "nil" {
			p.callValue(callback)
		}
		callback.Close()
	}()

	return 0
}
Exemplo n.º 8
0
func (p *Plugin) apiTimerNew(l *lua.State) int {
	callback := luar.NewLuaObject(l, 1)
	timeout := l.ToInteger(2)

	t := &Timer{
		cancel: make(chan bool),
	}

	go func() {
		defer func() {
			close(t.cancel)
			t.cancel = nil
		}()

		select {
		case <-time.After(time.Millisecond * time.Duration(timeout)):
			p.callValue(callback)
			callback.Close()
		case <-t.cancel:
		}
	}()

	obj := luar.NewLuaObjectFromValue(l, t)
	obj.Push()
	obj.Close()
	return 1
}
Exemplo n.º 9
0
func ExampleRegister_sandbox() {
	const code = `
    Print("foo")
    Print(io ~= nil)
    Print(os == nil)
`

	L := luar.Init()
	defer L.Close()

	res := L.LoadString(code)
	if res != 0 {
		msg := L.ToString(-1)
		fmt.Println("could not compile", msg)
	}

	// Create a empty sandbox.
	L.NewTable()
	// "*" means "use table on top of the stack."
	luar.Register(L, "*", luar.Map{
		"Print": fmt.Println,
	})
	env := luar.NewLuaObject(L, -1)
	G := luar.Global(L)

	// We can copy any Lua object from "G" to env with 'Set', e.g.:
	//   env.Set("print", G.Get("print"))
	// A more convenient and efficient way is to do a bulk copy with 'Setv':
	env.Setv(G, "print", "io")

	// Set up sandbox.
	L.SetfEnv(-2)

	// Run 'code' chunk.
	err := L.Call(0, 0)
	if err != nil {
		fmt.Println("could not run", err)
	}
	// Output:
	// foo
	// true
	// true
}
Exemplo n.º 10
0
func (p ProbeRunner) Run() {
	var err error
	var state *lua.State
	var fun *luar.LuaObject
	var res interface{}

	r := p.Error

	args := make(map[string]interface{})

	if err = json.Unmarshal([]byte(p.Probe.Arguments), &args); err != nil {
		goto out
	}

	state = mkstate()
	defer state.Close()

	err = state.DoString(fmt.Sprintf("fun = function(args) %s end", p.Script.Code))
	if err != nil {
		goto out
	}

	state.GetGlobal("fun")
	fun = luar.NewLuaObject(state, -1)

	if res, err = fun.Call(args); err != nil {
		goto out
	} else if res == nil {
		// if nil, that means no error. just go to out.
		goto out
	} else if status, ok := res.(string); !ok {
		// if it's not a string, that's bad. luar seems to convert go errors to strings..
		err = fmt.Errorf("script resulted in non-string return value %q", res)
	} else if status != "" {
		// if the string is not empty that's an error.
		err = fmt.Errorf("probe error: %s", status)
	}

out:
	r <- err
	close(r)
}
Exemplo n.º 11
0
func main() {
	L := luar.Init()
	defer L.Close()

	gettop := func() {
		fmt.Println("top", L.GetTop())
	}
	gettop()

	// compile chunk
	res := L.LoadString(test)
	if res != 0 {
		msg := L.ToString(-1)
		fmt.Println("could not compile", msg)
	}

	// create environment for chunk
	L.NewTable()
	// "*" means use table on stack....
	luar.Register(L, "*", luar.Map{
		"Print": fmt.Println,
	})
	env := luar.NewLuaObject(L, -1)
	G := luar.Global(L)
	//~ env.Set("print",G.Get("print"))
	//~ env.Set("io",G.Get("io"))
	// more convenient/efficient way to do a bulk copy
	env.Setv(G, "print", "io")
	L.SetfEnv(-2)

	// run chunk
	err := L.Call(0, 0)
	if err != nil {
		fmt.Println("could not run", err)
	}

}
Exemplo n.º 12
0
func (p *Plugin) apiOn(l *lua.State) int {
	event := strings.ToLower(l.CheckString(1))
	function := luar.NewLuaObject(l, 2)
	p.listeners[event] = append(p.listeners[event], function)
	return 0
}
Exemplo n.º 13
0
// Another way to do parse configs: using LuaObject to manipulate the table.
func ExampleNewLuaObject() {
	L := luar.Init()
	defer L.Close()

	// Using Lua to parse configuration files.
	const config = `return {
	baggins = true,
	age = 24,
	name = 'dumbo' ,
	marked = {1,2},
	options = {
		leave = true,
		cancel = 'always',
		tags = {strong=true, foolish=true},
	}
}`

	err := L.DoString(config)
	if err != nil {
		log.Fatal(err)
	}

	lo := luar.NewLuaObject(L, -1)
	// Can get the field itself as a Lua object, and so forth.
	opts := lo.GetObject("options")
	marked := lo.GetObject("marked")

	fmt.Printf("%#v\n", lo.Get("baggins"))
	fmt.Printf("%#v\n", lo.Get("name"))
	fmt.Printf("%#v\n", opts.Get("leave"))
	// Note that these Get methods understand nested fields.
	fmt.Printf("%#v\n", lo.Get("options.leave"))
	fmt.Printf("%#v\n", lo.Get("options.tags.strong"))
	// Non-existent nested fields don't crash but return nil.
	fmt.Printf("%#v\n", lo.Get("options.tags.extra.flakey"))
	fmt.Printf("%.1f\n", marked.Geti(1))

	iter := lo.Iter()
	keys := []string{}
	for iter.Next() {
		keys = append(keys, iter.Key.(string))
	}
	sort.Strings(keys)

	fmt.Println("Keys:")
	for _, v := range keys {
		fmt.Println(v)
	}
	// Output:
	// true
	// "dumbo"
	// true
	// true
	// true
	// <nil>
	// 1.0
	// Keys:
	// age
	// baggins
	// marked
	// name
	// options

}